package com.lyf.scm.admin.domain.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableList;
import com.lyf.scm.admin.api.dto.*;
import com.lyf.scm.admin.domain.excel.dto.SalesReadDTO;
import com.lyf.scm.admin.domain.excel.dto.SalesReadOtherDTO;
import com.lyf.scm.admin.domain.excel.dto.SalesWriteDTO;
import com.lyf.scm.admin.domain.remote.allocationservice.facade.*;
import com.lyf.scm.admin.domain.remote.basedata.dto.AreaDTO;
import com.lyf.scm.admin.domain.remote.basedata.dto.StoreDTO;
import com.lyf.scm.admin.domain.remote.basedata.facade.BaseDataFacade;
import com.lyf.scm.admin.domain.remote.bigdata.facade.BlOlapFacade;
import com.lyf.scm.admin.domain.remote.category.facade.CategoryFacade;
import com.lyf.scm.admin.domain.remote.item.dto.CategorySimpleDTO;
import com.lyf.scm.admin.domain.remote.item.dto.SkuInfoDTO;
import com.lyf.scm.admin.domain.remote.item.dto.SkuUnitExtDTO;
import com.lyf.scm.admin.domain.remote.item.facade.ItemCoreFacade;
import com.lyf.scm.admin.domain.service.PermissionService;
import com.lyf.scm.admin.domain.service.SalesPlanOtherService;
import com.lyf.scm.admin.domain.util.ExcelUtil;
import com.lyf.scm.admin.domain.util.OtherPlanDataListener;
import com.lyf.scm.admin.domain.util.OtherPlanDatasListener;
import com.lyf.scm.admin.domain.util.OtherTargetHandleUtil;
import com.lyf.scm.common.constants.CommonConstants;
import com.lyf.scm.common.enums.*;
import com.lyf.scm.common.model.ExcelExportDTO;
import com.lyf.scm.common.model.ExcelExportDataDTO;
import com.lyf.scm.common.util.AdvancedSearchUtil;
import com.lyf.scm.common.util.ExcelExportUtil;
import com.lyf.scm.common.util.date.MyDateUtil;
import com.lyf.scm.common.util.style.GeneralCellWriteHandler;
import com.rome.arch.core.exception.RomeException;
import com.rome.arch.util.IdWorker;
import com.rome.user.common.utils.UserContext;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * description:
 * 其他渠道计划serviceImpl
 *
 * @author: haodong
 * @data: 2020/7/31
 */
@Slf4j
@Service
public class SalesPlanOtherServiceImpl implements SalesPlanOtherService {

    @Resource
    private SalesPlanOtherFacade salesPlanOtherFacade;
    @Resource
    private SalesPlanEsFacade salesPlanEsFacade;
    @Resource
    private BaseDataFacade baseDataFacade;
    @Resource
    private ItemCoreFacade itemCoreFacade;
    @Resource
    private CategoryFacade categoryFacade;
    @Resource
    private BlOlapFacade blOlapFacade;
    @Resource
    private PermissionService permissionService;
    @Resource
    private OtherTargetGeneralHandlerFacade otherTargetGeneralHandlerFacade;
    @Resource
    private OperationLogRecordFacade operationLogRecordFacade;
    @Value("${filePath}")
    private String filePath;
    @Resource
    private SalesPlanEsLazyLoadingFacade salesPlanEsLazyLoadingFacade;

    /**
     * 查询参数转换查询对象
     *
     * @param salesPlanOther
     * @param channelCodes
     * @param level
     * @return
     */
    public EsAggregationDTO getEsDto(SalesPlanOtherDTO salesPlanOther, List<String> channelCodes, Integer level, Long userId) {
        //查询分层对应的商品
        //blOlapFacade.getLayeredData(salesPlanOther);
        EsAggregationDTO dto = new EsAggregationDTO();
        //DTO转queryDTO(查询条件)
        EsQueryDTO queryDTO = dtoToQueryDto(salesPlanOther, channelCodes);
        dto.setTableCode(TableCodeEnum.OTHER_PLAN.getCode());
        dto.setUnitType(salesPlanOther.getUnitType());
//        queryDTO.setPageNum(salesPlanOther.getPageNum());
//        queryDTO.setPageSize(salesPlanOther.getPageSize());
        dto.setPageSize(salesPlanOther.getPageSize());
        dto.setPageNum(salesPlanOther.getPageNum());
        dto.setUserId(userId);
        //分组参数
        List<String> groupList = getAllGroupList();
        dto.setGroupColumns(groupList);
        //获取聚合参数(指标)
        List<String> sumList = getSumList(level);
        dto.setSumColumns(sumList);
        dto.setEsQuery(queryDTO);
        dto.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
        return dto;
    }


    public List<String> getChannelList() {
        List<String> channelCodes = permissionService.getPermissionChannelList();
//        List<String> channelCodes = Arrays.asList("C00001");
        if (null == channelCodes) {
            throw new RomeException(ResponseMsg.FAIL_6009.getCode(), ResponseMsg.FAIL_6009.getMsg());
        }
        return channelCodes;
    }

    @Override
    public Integer getOtherPlanLevel() {
        Integer level = permissionService.getPermissionLevel();
//        Integer level = 2;
        if (null == level) {
            //level = 1;
            throw new RomeException(ResponseMsg.FAIL_2004.getCode(), ResponseMsg.FAIL_2004.getMsg());
        }
        return level;
    }

    /**
     * 按条件查询其他渠道计划(周)
     *
     * @param salesPlanOther
     * @return
     */
    @Override
    public PlanResponseDTO<SalesPlanOtherInfoDTO> listWeekBySelective(SalesPlanOtherDTO salesPlanOther) {
        //获取渠道权限集合
        List<String> channelCodes = getChannelList();
        //获取级别权限
        Integer level = getOtherPlanLevel();
        //根据日期获取间隔日期集合,没有结束时间，默认14周
        List<Map<String, Date>> weekDates = MyDateUtil.getWeekDates(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE);
        salesPlanOther.setWeekDateList(weekDates);
        salesPlanOther.setEndTime(MyDateUtil.getLastDate(null, weekDates));
        PlanResponseDTO<SalesPlanOtherInfoDTO> planResponse = new PlanResponseDTO<>();
        PageInfo<EsReturnDTO> listPageQuery = salesPlanEsLazyLoadingFacade.pageQuery(getEsDto(salesPlanOther, channelCodes, level, UserContext.getUserId()));
        if (null == listPageQuery) {
            return null;
        }
        List<EsReturnDTO> list = listPageQuery.getList();
        if (null == list) {
            return null;
        }
        //获取通用其它指标传输实体对象
        EsAggregationDTO esAggregationDTO = new EsAggregationDTO();
        esAggregationDTO.setGroupColumns(getGroupList(salesPlanOther));
        esAggregationDTO.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
        esAggregationDTO.setUnitType(salesPlanOther.getUnitType());
        OtherTargetGeneralQueryDTO queryDTO = OtherTargetHandleUtil.getGeneralQueryDTO(esAggregationDTO, list, OtherTargetsEnum.OTHER_PALN);
        OtherTargetHandleUtil.handleResult(otherTargetGeneralHandlerFacade.getNecessaryOtherTargets(queryDTO), list);
        List<SalesPlanOtherInfoDTO> dtoList = getNewTargetList(list, level, null);
        planResponse.setPageNum(listPageQuery.getPageNum());
        planResponse.setHasNextPage(listPageQuery.isHasNextPage());
        planResponse.setInfoList(dtoList);
        //格式化日期格式
        planResponse.setDateList(MyDateUtil.processCyclesDate(weekDates, "M.dd"));
        return planResponse;
    }


    /**
     * 图表数据接口
     *
     * @param salesPlanOther
     * @return
     */
    @Override
    public PlanResponseDTO<SalesPlanOtherInfoDTO> eChartsData(SalesPlanOtherDTO salesPlanOther) {
        //获取渠道权限集合
        List<String> channelCodes = getChannelList();
        //获取级别权限
        Integer level = getOtherPlanLevel();
        Date startTime = salesPlanOther.getStartTime();
        Date endTime = salesPlanOther.getEndTime();

        List<Map<String, Date>> cyclesDates;
        if (null != endTime) {
            cyclesDates = MyDateUtil.getWeekDates(startTime, endTime);
            salesPlanOther.setWeekDateList(cyclesDates);
        } else {
            //没有结束时间，默认14周
            cyclesDates = MyDateUtil.getWeekDates(startTime, CommonConstants.WEEK_SIZE);
            salesPlanOther.setWeekDateList(cyclesDates);
            salesPlanOther.setEndTime(MyDateUtil.getLastDate(null, cyclesDates));
        }
        //blOlapFacade.getLayeredData(salesPlanOther);
        EsAggregationDTO dto = new EsAggregationDTO();
        //DTO转queryDTO
        EsQueryDTO queryDTO = dtoToQueryDto(salesPlanOther, channelCodes);
        dto.setUnitType(salesPlanOther.getUnitType());
        //获取聚合参数
        List<String> sumList = getSumList(level);
        dto.setSumColumns(sumList);
        dto.setEsQuery(queryDTO);
        dto.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
        PlanResponseDTO<SalesPlanOtherInfoDTO> planResponse = new PlanResponseDTO<>();
        PageInfo<EsReturnDTO> listPageQuery = salesPlanEsFacade.queryByGroup(dto);
        if (null == listPageQuery) {
            return null;
        }
        List<EsReturnDTO> list = listPageQuery.getList();
        //获取通用其它指标传输实体对象
        OtherTargetGeneralQueryDTO otherQueryDTO = OtherTargetHandleUtil.getGeneralEchartQueryDTO(dto, OtherTargetsEnum.OTHER_PALN, null);
        otherQueryDTO.setType(CommonConstants.ONE);
        OtherTargetHandleUtil.handleEchartResult(otherTargetGeneralHandlerFacade.getEchartNecessaryOtherTargets(otherQueryDTO), list.get(0).getTargetMap());
        List<SalesPlanOtherInfoDTO> dtoList = getNewTargetList(list, level, CommonConstants.ONE);
        planResponse.setInfoList(dtoList);
        planResponse.setDateList(MyDateUtil.processCyclesDate(cyclesDates, "M.dd"));
        return planResponse;
    }

    public ExcelExportDataDTO exportData(SalesPlanOtherDTO salesPlanOther, Integer type, Integer level, List<String> channelCodes, List<Integer> rowIndex, Long userId) {
        // 获取日期标题
        List<String> dateTitles = MyDateUtil.processCyclesDate(salesPlanOther.getWeekDateList(), "MM.dd");
        //增加合计
        dateTitles.add("合计");
        List<List<Object>> exportDataList = new ArrayList<>();
        //指标名称集合
        List<String> allTargetsDesc = SalesPlanOtherEnum.getAllTargetsDesc(level);
        List<SalesPlanOtherInfoDTO> salesPlan = new ArrayList<>();
        //导出当前页、勾选导出
        if (!ExcelExportTypeEnum.SEARCHED_DATA_EXPORT.getType().equals(type)) {
            /*PageInfo<EsReturnDTO> listPageQuery = salesPlanEsFacade.queryByGroup(getEsDto(salesPlanOther, channelCodes, level, userId));
            List<EsReturnDTO> list = listPageQuery.getList();*/
            EsAggregationDTO dto = getEsDto(salesPlanOther, channelCodes, level, userId);
            //从缓存中拿导出数据
            List<EsReturnDTO> list = salesPlanEsLazyLoadingFacade.queryFromCache(dto);
            if (CollectionUtils.isEmpty(list)) {
                throw new RomeException(ResponseMsg.FAIL_2005.getCode(), ResponseMsg.FAIL_2005.getMsg());
            }
            EsAggregationDTO esAggregationDTO = new EsAggregationDTO();
            esAggregationDTO.setGroupColumns(getGroupList(salesPlanOther));
            esAggregationDTO.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
            esAggregationDTO.setUnitType(salesPlanOther.getUnitType());
            //获取通用其它指标传输实体对象
            OtherTargetGeneralQueryDTO queryDTO = OtherTargetHandleUtil.getGeneralQueryDTO(esAggregationDTO, list, OtherTargetsEnum.OTHER_PALN);
            OtherTargetHandleUtil.handleResult(otherTargetGeneralHandlerFacade.getNecessaryOtherTargets(queryDTO), list);
            salesPlan = getNewTargetList(list, level, null);
            if (ExcelExportTypeEnum.CURRENT_PAGE_EXPORT.getType().equals(type)) {
                this.getExcelList(exportDataList, salesPlan, allTargetsDesc, dateTitles, null);
            } else {
                this.getExcelList(exportDataList, salesPlan, allTargetsDesc, dateTitles, rowIndex);
            }
        } else {
            EsExportAggregationDTO exportDto = new EsExportAggregationDTO();
            //DTO转queryDTO(查询条件)
            EsQueryDTO queryDTO = dtoToQueryDto(salesPlanOther, channelCodes);
            exportDto.setUnitType(salesPlanOther.getUnitType());
            exportDto.setAfterKey("");
            exportDto.setPageNum(salesPlanOther.getPageNum());
            exportDto.setPageSize(salesPlanOther.getPageSize());
            //分组参数
            List<String> groupList = getAllGroupList();
            exportDto.setGroupColumns(groupList);
            //获取聚合参数(指标)
            List<String> sumList = getSumList(level);
            exportDto.setSumColumns(sumList);
            exportDto.setEsQuery(queryDTO);
            exportDto.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
            //全部数据导出
            EsScrollReturnDTO esScrollReturnDTO;
            EsAggregationDTO esAggregationDTO = new EsAggregationDTO();
            esAggregationDTO.setGroupColumns(getGroupList(salesPlanOther));
            esAggregationDTO.setDateList(MyDateUtil.getDateLists(salesPlanOther.getStartTime(), CommonConstants.WEEK_SIZE));
            esAggregationDTO.setUnitType(salesPlanOther.getUnitType());
            do {
                esScrollReturnDTO = salesPlanEsFacade.exportByGroup(exportDto);
                //this.getExportDataList(exportDataList, this.getExportList(dates, esScrollReturnDTO.getEsReturnDTOList(), weekDates), allTargetsDesc);
                List<EsReturnDTO> list = esScrollReturnDTO.getEsReturnDTOList();
                //获取通用其它指标传输实体对象
                if (CollectionUtils.isNotEmpty(list)) {
                    OtherTargetGeneralQueryDTO otherQueryDTO = OtherTargetHandleUtil.getGeneralQueryDTO(esAggregationDTO, list, OtherTargetsEnum.OTHER_PALN);
                    OtherTargetHandleUtil.handleResult(otherTargetGeneralHandlerFacade.getNecessaryOtherTargets(otherQueryDTO), list);
                }
                salesPlan = getNewTargetList(list, level, null);
                this.getExcelList(exportDataList, salesPlan, allTargetsDesc, dateTitles, rowIndex);
                exportDto.setAfterKey(esScrollReturnDTO.getAfterKey());
            } while (esScrollReturnDTO.getAfterKey() != null);
        }
        if (CollectionUtils.isEmpty(exportDataList)) {
            throw new RomeException(ResponseMsg.FAIL_2005.getCode(), ResponseMsg.FAIL_2005.getMsg());
        }
        List<List<String>> heads = new ArrayList<>();
        int mergeCellsColumns = this.setExcelTitles(heads, dateTitles);
        return ExcelExportUtil.getExcelExportData(mergeCellsColumns, exportDataList, heads, allTargetsDesc.size(), new GeneralCellWriteHandler());
    }

    private void getExcelList(List<List<Object>> exportDataList, List<SalesPlanOtherInfoDTO> salesPlan, List<String> targets, List<String> dateTitles, List<Integer> indexs) {
        if (CollectionUtils.isEmpty(salesPlan)) {
            return;
        }

        boolean flag = false;
        if (indexs != null && indexs.size() > 0) {
            flag = true;
        }
        List<SalesPlanOtherInfoDTO> salesPlanOtherInfoList = new ArrayList<>();
        int index = 0;
        //将分组后的数据汇总
        for (SalesPlanOtherInfoDTO key : salesPlan) {
            if (flag && !indexs.contains(index)) {
                index++;
                continue;
            }
            index++;
            for (int i = 0; i < targets.size(); i++) {
                List<Object> itemRow = new ArrayList<>();
                //加入渠道，区域，品类，商品  信息
                itemRow.add(key.getChannel());
                itemRow.add(key.getType());
                itemRow.add(key.getArea());
                itemRow.add(key.getCategory());
                itemRow.add(key.getSkuName());
                //加入指标
                itemRow.add(targets.get(i));
                //导入人没有下级确认量
                if (targets.size() == 7) {
                    //加入数据()
                    for (int j = 0; j < (dateTitles.size() - 1); j++) {
                        //获取指标集合，这里没有排序，默认使用枚举的顺序
                        switch (i) {
                            case 0:
                                itemRow.add(key.getLastPlanQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getLastPlanQtys().get(j));
                                break;
                            case 1:
                                itemRow.add(key.getLastConfirmedQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getLastConfirmedQtys().get(j));
                                break;
                            case 2:
                                itemRow.add(key.getPlanQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getPlanQtys().get(j));
                                break;
                            case 3:
                                itemRow.add(key.getConfirmedQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getConfirmedQtys().get(j));
                                break;
                            case 4:
                                itemRow.add(key.getPlanDifferences().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getPlanDifferences().get(j));
                                break;
                            case 5:
                                itemRow.add(key.getPlanProportions().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : (key.getPlanProportions().get(j).multiply(new BigDecimal(100)).setScale(3, BigDecimal.ROUND_HALF_UP)) + "%");
                                break;
                            case 6:
                                itemRow.add(key.getActualSalesQty().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getActualSalesQty().get(j));
                                break;
                            default:
                                break;
                        }
                    }
                } else {
                    //加入数据
                    for (int j = 0; j < (dateTitles.size() - 1); j++) {
                        //获取指标集合，这里没有排序，默认使用枚举的顺序
                        switch (i) {
                            case 0:
                                itemRow.add(key.getLastPlanQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getLastPlanQtys().get(j));
                                break;
                            case 1:
                                itemRow.add(key.getLastConfirmedQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getLastConfirmedQtys().get(j));
                                break;
                            case 2:
                                itemRow.add(key.getPlanQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getPlanQtys().get(j));
                                break;
                            case 3:
                                itemRow.add(key.getSubordinateConfirmedQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getSubordinateConfirmedQtys().get(j));
                                break;
                            case 4:
                                itemRow.add(key.getConfirmedQtys().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getConfirmedQtys().get(j));
                                break;
                            case 5:
                                itemRow.add(key.getPlanDifferences().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getPlanDifferences().get(j));
                                break;
                            case 6:
                                itemRow.add(key.getPlanProportions().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : (key.getPlanProportions().get(j).multiply(new BigDecimal(100)).setScale(3, BigDecimal.ROUND_HALF_UP)) + "%");
                                break;
                            case 7:
                                itemRow.add(key.getActualSalesQty().get(j).compareTo(BigDecimal.ZERO) == 0 ? "-" : key.getActualSalesQty().get(j));
                                break;
                            default:
                                break;
                        }
                    }
                }
                //合计
                BigDecimal total = BigDecimal.ZERO;
                String percentage = "";
                //获取除日期外的下标
                int indexa = itemRow.size() - (dateTitles.size() - 1);
                List<Object> numRow = new ArrayList<>();
                numRow.addAll(itemRow);
                for (int a = 0; a < indexa; a++) {
                    numRow.remove(numRow.get(0));
                }
                //循环增加查询的日期对应指标数量
                for (Object obj : numRow) {
                    BigDecimal num = BigDecimal.ZERO;
                    if ("-".equals(obj)) {
                        num = BigDecimal.ZERO;
                        total = total.add(num);
                    } else {
                        if (obj.toString().contains("%")) {
                            String nums = obj.toString().substring(0, obj.toString().length() - 1);
                            num = new BigDecimal(nums);
                            total = total.add(num);
                            percentage = total + "%";
                        } else {
                            num = new BigDecimal(obj.toString());
                            total = total.add(num);
                        }
                    }
                }
                if ("".equals(percentage)) {
                    itemRow.add(total.equals(BigDecimal.ZERO) ? "-" : total);
                } else {
                    itemRow.add(percentage);
                }
                exportDataList.add(itemRow);
            }
        }
    }

    private int setExcelTitles(List<List<String>> heads, List<String> dateTitles) {
        //获取高级搜索标题
        this.getExcelAdvancedSearchTitle(heads);
        int result = heads.size();
        //加入指标标题
        List<String> targetTitle = new ArrayList<>();
        targetTitle.add(ExcelExportTitleEnum.TARGET_TITLE.getTitle());
        heads.add(targetTitle);
        //加入日期标题
        AdvancedSearchUtil.getExcelDateTitle(heads, dateTitles);
        return result;
    }

    private void getExcelAdvancedSearchTitle(List<List<String>> heads) {
        setList(heads, ExcelExportTitleEnum.CHANNEL_TITLE.getTitle());
        setList(heads, ExcelExportTitleEnum.PLAN_TITLE.getTitle());
        setList(heads, ExcelExportTitleEnum.AREA_TITLE.getTitle());
        setList(heads, ExcelExportTitleEnum.CATEGORY_TITLE.getTitle());
        setList(heads, ExcelExportTitleEnum.SKU_TITLE.getTitle());
    }

    /**
     * 获取标题行list
     *
     * @param heads
     * @param title
     */
    private static void setList(List<List<String>> heads, String title) {
        List<String> list = new ArrayList<>();
        list.add(title);
        heads.add(list);
    }

    private List<String> getAllGroupList() {
        List<String> groupList = new ArrayList<>();
        groupList.add(EsConmulEnum.CHANNEL_KEYWORD.getFName());
        groupList.add(EsConmulEnum.PLAN_TYPE.getFName());
        groupList.add(EsConmulEnum.PROVINCE_CODE_KEYWORD.getFName());
        groupList.add(EsConmulEnum.CITY_CODE_KEYWORD.getFName());
        groupList.add(EsConmulEnum.COUNTY_CODE_KEYWORD.getFName());
        groupList.add(EsConmulEnum.STORE_KEYWORD.getFName());
        groupList.add(EsConmulEnum.SKU_KEYWORD.getFName());
        return groupList;
    }

    private List<String> getGroupList(SalesPlanOtherDTO salesPlanOther) {
        List<String> groupList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(salesPlanOther.getChannelCodeList())) {
            groupList.add(EsConmulEnum.CHANNEL_KEYWORD.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getTypeList())) {
            groupList.add(EsConmulEnum.PLAN_TYPE.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getProvinceCodeList())) {
            groupList.add(EsConmulEnum.PROVINCE_CODE_KEYWORD.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getCityCodeList())) {
            groupList.add(EsConmulEnum.CITY_CODE_KEYWORD.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getCountyCodeList())) {
            groupList.add(EsConmulEnum.COUNTY_CODE_KEYWORD.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getStoreCodeList())) {
            groupList.add(EsConmulEnum.STORE_KEYWORD.getFName());
        }
        if (CollectionUtil.isNotEmpty(salesPlanOther.getSkuCodeList())) {
            groupList.add(EsConmulEnum.SKU_KEYWORD.getFName());
        }
        return groupList;
    }

    private List<String> getSumList(Integer level) {
        List<String> sumList = new ArrayList<>();
        if (CommonConstants.ONE.equals(level)) {
            sumList.add(EsSumColumnEnum.LAST_CONFIRM_L3.getColumn());
            sumList.add(EsSumColumnEnum.CONFIRM_L3.getColumn());
            sumList.add(EsSumColumnEnum.PREDICT_CONFIRM_L3_DIFFERENCE.getColumn());
            sumList.add(EsSumColumnEnum.PREDICT_CONFIRM_L3_SCALE.getColumn());
        } else {
            sumList.add(EsSumColumnEnum.LAST_CONFIRM_L4.getColumn());
            sumList.add(EsSumColumnEnum.CONFIRM_L4.getColumn());
            sumList.add(EsSumColumnEnum.CONFIRM_L3.getColumn());
            sumList.add(EsSumColumnEnum.PREDICT_CONFIRM_L4_DIFFERENCE.getColumn());
            sumList.add(EsSumColumnEnum.PREDICT_CONFIRM_L4_SCALE.getColumn());
        }
        sumList.add(EsSumColumnEnum.LAST_PREDICT_SALES.getColumn());
        sumList.add(EsSumColumnEnum.PREDICT_SALES.getColumn());
        sumList.add(EsSumColumnEnum.CONFIRM_STATUS_L4.getColumn());
        return sumList;
    }

    private EsQueryDTO dtoToQueryDto(SalesPlanOtherDTO salesPlanOther, List<String> channelCodes) {
        EsQueryDTO dto = new EsQueryDTO();
        dto.setStartDate(DateUtil.formatDate(salesPlanOther.getStartTime()));
        dto.setEndDate(DateUtil.formatDate(salesPlanOther.getEndTime()));
        dto.setChannelCodeList(salesPlanOther.getChannelCodeList());
        dto.setPermissionChannelList(channelCodes);
        dto.setQueryAreaCodeList(salesPlanOther.getAreaCodeList());
        dto.setCategoryCodeList(salesPlanOther.getCategoryCodeList());
        List<String> typeList = SalesOtherTypeEnum.getCodeListByType(CommonConstants.ONE);
        if (CollectionUtil.isNotEmpty(salesPlanOther.getTypeList())) {
            dto.setTypeList(salesPlanOther.getTypeList());
        } else {
            dto.setTypeList(typeList);
        }
        return dto;
    }

    /**
     * 手工导入销售计划
     *
     * @param file
     * @param type
     * @return
     */
    @Override
    public Integer importPlanType(MultipartFile file, String type) {
        //校验标题日期是否正确
        //对象集合
        List<SalesPlanOtherDTO> salesOtherList = new ArrayList<>();
        //随机id
        IdWorker idWorker = new IdWorker();
        //导入类型
        Integer impType = 1;
        //校验数据是否正确
        Boolean ifTrue;
        //获取标识
        Long identification = idWorker.getId();
        //记录到操作日志表
        OperationLogRecordDTO operationDto = new OperationLogRecordDTO();
        operationDto.setOpType(OperationTypeEnum.IMPORT.getType());
        //默认处理中
        operationDto.setOpStatus(OperationStatusEnum.PROCESSING.getType());
        operationDto.setOpSource(OperationSourceEnum.FOUR_PLAN.getTableType());
        operationDto.setCreator(UserContext.getUserId());
        operationDto.setCreatorName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
        operationDto.setModifier(UserContext.getUserId());
        operationDto.setModifierName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
        //需要拆分成门店的省份集合
        List<AreaDTO> provinceList = new ArrayList<>();
        //需要拆分成门店的城市集合
        List<AreaDTO> cityNameList = new ArrayList<>();
        //拆分门店对应的省名称集合
        List<AreaDTO> provinceNameListByCity = new ArrayList<>();
        //门店集合
        List<StoreDTO> storeList = new ArrayList<>();
        //门店对应的省份集合（不用拆分）
        List<AreaDTO> provinceListByStore = new ArrayList<>();
        //门店对应的城市集合（不用拆分）
        List<AreaDTO> cityListByStore = new ArrayList<>();
        //门店对应的县/区集合（不用拆分）
        List<AreaDTO> countyListByStore = new ArrayList<>();
        //读取模板
        List<SalesReadDTO> salesReadList = new ArrayList<>();
        List<SalesReadOtherDTO> salesOtherReadList = new ArrayList<>();
        //有门店（新品、销售计划加盟、直营）
        if (SalesPlanTypeEnum.PLAN_SIXTEEN.getType().equals(type) || SalesPlanTypeEnum.PLAN_ELEVEN.getType().equals(type) || SalesPlanTypeEnum.PLAN_SEVENTEEN.getType().equals(type)) {
            //校验标题周期是否正确
            OtherPlanDataListener otherPlanDataListener = new OtherPlanDataListener();
            try {
                EasyExcel.read(file.getInputStream(), SalesReadDTO.class, otherPlanDataListener).sheet().headRowNumber(1).doRead();
                salesReadList = ExcelUtil.readExcel(file.getInputStream(), SalesReadDTO.class);
            } catch (IOException e) {
                throw new RomeException(ResponseMsg.FAIL_2046.getCode(), ResponseMsg.FAIL_2046.getMsg());
            } catch (Exception e) {
                throw new RomeException(ResponseMsg.FAIL_2045.getCode(), ResponseMsg.FAIL_2045.getMsg());
            }
            //单次导入不能超过10000行
            if (salesReadList.size() > CommonConstants.PLAN_OTHER_IMPORT_MAX) {
                throw new RomeException(ResponseMsg.FAIL_2003.getCode(), ResponseMsg.FAIL_2003.getMsg());
            }
        } else {
            //校验标题周期是否正确
            OtherPlanDatasListener otherPlanDatasListener = new OtherPlanDatasListener();
            try {
                EasyExcel.read(file.getInputStream(), SalesReadOtherDTO.class, otherPlanDatasListener).sheet().headRowNumber(1).doRead();
                salesOtherReadList = ExcelUtil.readExcel(file.getInputStream(), SalesReadOtherDTO.class);
            } catch (IOException e) {
                throw new RomeException(ResponseMsg.FAIL_2046.getCode(), ResponseMsg.FAIL_2046.getMsg());
            } catch (Exception e) {
                throw new RomeException(ResponseMsg.FAIL_2045.getCode(), ResponseMsg.FAIL_2045.getMsg());
            }
            //单次导入不能超过10000行
            if (salesOtherReadList.size() > CommonConstants.PLAN_OTHER_IMPORT_MAX) {
                throw new RomeException(ResponseMsg.FAIL_2003.getCode(), ResponseMsg.FAIL_2003.getMsg());
            }
        }
        List<SalesPlanOtherDTO> dtoList = new ArrayList<>();
        if (!SalesPlanTypeEnum.PLAN_FIFTEEN.getType().equals(type) && !SalesPlanTypeEnum.PLAN_SIXTEEN.getType().equals(type)) {
            //导入销售计划(加盟、云商、经销中心、APP)
            impType = 1;
            String channelName = "";
            //销售计划(加盟,直营)
            if (type.equals(SalesPlanTypeEnum.PLAN_ELEVEN.getType()) || SalesPlanTypeEnum.PLAN_SEVENTEEN.getType().equals(type)) {
                //获取导入数据中去重后的渠道code集合
                List<String> channelCodeList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getChannelCode())).map(SalesReadDTO::getChannelCode).distinct().collect(Collectors.toList());
                //一种计划类型只能导入一种渠道
                if (channelCodeList.size() > 1) {
                    throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                }
                salesReadList.forEach(item -> {
                    //校验
                    checkData(item, CommonConstants.ONE);
                });
                //获取所有省份为江苏省的数据
                List<SalesReadDTO> simpleList = salesReadList.stream().filter(item -> CommonConstants.PRO_NAME.contains(item.getProvinceName())).distinct().collect(Collectors.toList());
                simpleList.forEach(item -> {
                    //省份为江苏省，城市不能为空
                    if (ObjectUtil.isNull(item.getCityName())) {
                        throw new RomeException(ResponseMsg.PARAM_ERROR_2009.getCode(), ResponseMsg.PARAM_ERROR_2009.getMsg());
                    }
                });
                //加盟
                if (type.equals(SalesPlanTypeEnum.PLAN_ELEVEN.getType())) {
                    if (!ChannelTypeEnum.JOIN_IN.getCode().equals(channelCodeList.get(0))) {
                        throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                    }
                    channelName = ChannelTypeEnum.JOIN_IN.getDesc();
                } else {
                    if (!ChannelTypeEnum.DIRECTLY_OPERATE.getCode().equals(channelCodeList.get(0))) {
                        throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                    }
                    channelName = ChannelTypeEnum.DIRECTLY_OPERATE.getDesc();
                    type = SalesOtherTypeEnum.PLAN_SIXTEEN.getType();
                }
                //获取到门店的数据（校验商品是否可以叫货）
                //checkChannelSkuPermit(salesReadList, null, CommonConstants.ZERO);
                //获取导入数据中去重后的商品code集合
                List<String> skuCodeList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getSkuCode())).map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                List<SkuUnitExtDTO> skuUnitList = itemCoreFacade.getSkuUnitByCodeAndType(skuCodeList, 5);
                ifTrue = skuUnitList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuUnitList.stream().map(SkuUnitExtDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2033.getCode(), ResponseMsg.FAIL_2033.getMsg() + list);
                }
                //根据商品code集合获取商品对应品类id集合(接口最多一次只能调100个)
                List<SkuInfoDTO> skus = new ArrayList<>();
                int perThreadHandleCount = 100;
                int countNum = 0;
                while (countNum < skuCodeList.size()) {
                    countNum += perThreadHandleCount;
                    List<String> dtos = ImmutableList.copyOf(skuCodeList.subList(countNum - perThreadHandleCount,
                            countNum < skuCodeList.size() ? countNum : skuCodeList.size()));
                    List<SkuInfoDTO> skuInfos = itemCoreFacade.getAllCategoryIdBySkuCode(1, dtos.size(), dtos).getList();
                    skus.addAll(skuInfos);
                }
                ifTrue = skus.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skus.stream().map(SkuInfoDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2032.getCode(), ResponseMsg.FAIL_2032.getMsg() + list);
                }
                List<Integer> ids = skus.stream().filter(f -> ObjectUtil.isNotNull(f.getCategoryId())).map(SkuInfoDTO::getCategoryId).distinct().collect(Collectors.toList());
                //查询出所有商品code对应的品类信息
                List<CategorySimpleDTO> categorys = itemCoreFacade.getAllCategoryByCategoryId(ids);
                operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_ELEVEN.getDesc());
                //获取所有不重复省份的名称
                List<String> provinceNams = salesReadList.stream().map(SalesReadDTO::getProvinceName).distinct().collect(Collectors.toList());
                provinceList = baseDataFacade.listProvinceByList(provinceNams);
                ifTrue = provinceList.size() == provinceNams.size();
                if (!ifTrue) {
                    List<String> proSt = provinceList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                    List<String> list = provinceNams.stream().filter(item -> !proSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + list);
                }
                //获取所有不重复城市的名称
                List<String> cityNames = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName())).map(SalesReadDTO::getCityName).distinct().collect(Collectors.toList());
                if (cityNames.size() > 0) {
                    //根据城市名称获取城市信息
                    cityNameList = baseDataFacade.listProvinceByList(cityNames);
                    ifTrue = cityNameList.size() == cityNames.size();
                    if (!ifTrue) {
                        List<String> citySt = cityNameList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                        List<String> list = cityNames.stream().filter(item -> !citySt.contains(item)).collect(Collectors.toList());
                        throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + list);
                    }
                    //获取省份编码
                    List<String> provinces = cityNameList.stream().map(AreaDTO::getParentCode).collect(Collectors.toList());
                    if (provinces.size() > 0) {
                        provinceNameListByCity = baseDataFacade.listAreaInfoByCode(provinces);
                    }
                }
                //获取表格中所有有门店的数据
                List<SalesReadDTO> stores = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getStoreCode())).distinct().collect(Collectors.toList());
                if (stores.size() > 0) {
                    List<String> storeCodes = stores.stream().map(SalesReadDTO::getStoreCode).distinct().collect(Collectors.toList());
                    //获取基础服务中心所有门店
                    storeList = baseDataFacade.listStore(new StoreDTO()).getList();
                    //筛选出表格中的门店
                    storeList = storeList.stream().filter(f -> storeCodes.contains(f.getCode())).collect(Collectors.toList());
                    List<String> stos = storeList.stream().map(StoreDTO::getCode).collect(Collectors.toList());
                    List<String> noStoreList = storeCodes.stream().filter(item -> !stos.contains(item)).collect(Collectors.toList());
                    if (noStoreList.size() > 0) {
                        throw new RomeException(ResponseMsg.FAIL_2013.getCode(), ResponseMsg.FAIL_2013.getMsg() + ",错误门店code：" + noStoreList);
                    }
                    //加盟
                    if (type.equals(SalesPlanTypeEnum.PLAN_ELEVEN.getType())) {
                        //加盟
                        List<String> failStoreJoinList = new ArrayList<>();
                        storeList.forEach(item -> {
                            if (!ShopTypeEnum.JOIN_SHOP.getStoreProperties().equals(item.getStoreProperties()) && !ShopTypeEnum.JOIN_TRUSTEESHIP_SHOP.getStoreProperties().equals(item.getStoreProperties())) {
                                failStoreJoinList.add(item.getCode());
                            }
                        });
                        if (failStoreJoinList.size() > 0) {
                            throw new RomeException(ResponseMsg.FAIL_2024.getCode(), ResponseMsg.FAIL_2024.getMsg() + "，错误门店code：" + failStoreJoinList);
                        }
                    } else {
                        //直营
                        List<String> failStoreList = new ArrayList<>();
                        storeList.forEach(item -> {
                            if (!ShopTypeEnum.DIRECTLY_SHOP.getStoreProperties().equals(item.getStoreProperties()) && !ShopTypeEnum.NON_BRANCH_SHOP.getStoreProperties().equals(item.getStoreProperties()) && !ShopTypeEnum.POOL_SHOP.getStoreProperties().equals(item.getStoreProperties())) {
                                failStoreList.add(item.getCode());
                            }
                        });
                        if (failStoreList.size() > 0) {
                            throw new RomeException(ResponseMsg.FAIL_2029.getCode(), ResponseMsg.FAIL_2029.getMsg() + "，错误门店code：" + failStoreList);
                        }
                    }
                    //获取不重复
                    List<String> provinceCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getProvinceCode())).map(StoreDTO::getProvinceCode).distinct().collect(Collectors.toList());
                    List<String> cityCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getCityCode())).map(StoreDTO::getCityCode).distinct().collect(Collectors.toList());
                    List<String> countyCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getAreaCode())).map(StoreDTO::getAreaCode).distinct().collect(Collectors.toList());
                    //根据code批量获取省市区信息
                    if (provinceCodes.size() > 0) {
                        provinceListByStore = baseDataFacade.listAreaInfoByCode(provinceCodes);
                    }
                    if (cityCodes.size() > 0) {
                        cityListByStore = baseDataFacade.listAreaInfoByCode(cityCodes);
                    }
                    if (countyCodes.size() > 0) {
                        countyListByStore = baseDataFacade.listAreaInfoByCode(countyCodes);
                    }
                }
                //表格数据转换为DTO集合
                dtoList = this.getDtoList(salesReadList, type, channelName, skus, categorys, provinceList, cityNameList
                        , storeList, provinceListByStore, cityListByStore, countyListByStore, provinceNameListByCity, skuUnitList);
            }
            //云商（营销计划、新品铺货计划）、APP（新品铺货计划）、经销中心（营销计划、新品铺货计划）
            else {
                //获取导入数据中去重后的渠道code集合
                List<String> channelCodeList = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getChannelCode())).map(SalesReadOtherDTO::getChannelCode).distinct().collect(Collectors.toList());
                //一种计划类型只能导入一种渠道
                if (channelCodeList.size() > 1) {
                    throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                }
                salesOtherReadList.forEach(item -> {
                    //校验数据
                    checkOtherData(item, CommonConstants.ONE);
                });
                //获取所有省份为江苏省的数据
                List<SalesReadOtherDTO> simpleList = salesOtherReadList.stream().filter(item -> CommonConstants.PRO_NAME.contains(item.getProvinceName())).distinct().collect(Collectors.toList());
                simpleList.forEach(item -> {
                    //省份为江苏省，城市不能为空
                    if (ObjectUtil.isNull(item.getCityName())) {
                        throw new RomeException(ResponseMsg.PARAM_ERROR_2009.getCode(), ResponseMsg.PARAM_ERROR_2009.getMsg());
                    }
                });

                //校验数据到省或市的商品是否有叫货权
                //checkChannelSkuPermit(null, salesOtherReadList, CommonConstants.ONE);
                //获取导入数据中去重后的商品code集合
                List<String> skuCodeList = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getSkuCode())).map(SalesReadOtherDTO::getSkuCode).distinct().collect(Collectors.toList());
                List<SkuUnitExtDTO> skuUnitList = itemCoreFacade.getSkuUnitByCodeAndType(skuCodeList, 5);
                ifTrue = skuUnitList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuUnitList.stream().map(SkuUnitExtDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2033.getCode(), ResponseMsg.FAIL_2033.getMsg() + list);
                }
                /*List<SkuPurchasePermitDTO> skuPurchaseList = categoryFacade.querySkuPermit(skuCodeList);
                ifTrue = skuPurchaseList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuPurchaseList.stream().map(SkuPurchasePermitDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.PARAM_ERROR_2006.getCode(), ResponseMsg.PARAM_ERROR_2006.getMsg() + "，错误编码为：" + list);
                }
                List<String> permitList = new ArrayList<>();
                skuPurchaseList.forEach(e -> {
                    //如果商品编码不是当前渠道可下单商品
                    if (!e.getPermit()) {
                        permitList.add(e.getSkuCode());
                    }
                });
                if (permitList.size() > 0) {
                    throw new RomeException(ResponseMsg.PARAM_ERROR_2007.getCode(), ResponseMsg.PARAM_ERROR_2007.getMsg() + "，错误编码为：" + permitList);
                }*/

                //根据商品code集合获取商品对应品类id集合(接口最多一次只能调100个)
                List<SkuInfoDTO> skus = new ArrayList<>();
                int perThreadHandleCount = 100;
                int countNum = 0;
                while (countNum < skuCodeList.size()) {
                    countNum += perThreadHandleCount;
                    List<String> dtos = ImmutableList.copyOf(skuCodeList.subList(countNum - perThreadHandleCount,
                            countNum < skuCodeList.size() ? countNum : skuCodeList.size()));
                    List<SkuInfoDTO> skuInfos = itemCoreFacade.getAllCategoryIdBySkuCode(1, dtos.size(), dtos).getList();
                    skus.addAll(skuInfos);
                }
                ifTrue = skus.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skus.stream().map(SkuInfoDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2032.getCode(), ResponseMsg.FAIL_2032.getMsg() + list);
                }
                List<Integer> ids = skus.stream().filter(f -> ObjectUtil.isNotNull(f.getCategoryId())).map(SkuInfoDTO::getCategoryId).distinct().collect(Collectors.toList());
                //查询出所有商品code对应的品类信息
                List<CategorySimpleDTO> categorys = itemCoreFacade.getAllCategoryByCategoryId(ids);

                //获取所有不重复省份的名称
                List<String> provinceNams = salesOtherReadList.stream().map(SalesReadOtherDTO::getProvinceName).distinct().collect(Collectors.toList());
                provinceList = baseDataFacade.listProvinceByList(provinceNams);
                ifTrue = provinceList.size() == provinceNams.size();
                if (!ifTrue) {
                    List<String> proSt = provinceList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                    List<String> list = provinceNams.stream().filter(item -> !proSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + list);
                }
                //获取所有不重复城市的名称
                List<String> cityNames = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName())).map(SalesReadOtherDTO::getCityName).distinct().collect(Collectors.toList());
                if (cityNames.size() > 0) {
                    //根据城市名称获取城市信息
                    cityNameList = baseDataFacade.listProvinceByList(cityNames);
                    ifTrue = cityNameList.size() == cityNames.size();
                    if (!ifTrue) {
                        List<String> citySt = cityNameList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                        List<String> list = cityNames.stream().filter(item -> !citySt.contains(item)).collect(Collectors.toList());
                        throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + list);
                    }
                    //获取省份编码
                    List<String> provinces = cityNameList.stream().map(AreaDTO::getParentCode).collect(Collectors.toList());
                    if (provinces.size() > 0) {
                        provinceNameListByCity = baseDataFacade.listAreaInfoByCode(provinces);
                    }
                }
                //云商
                if (type.equals(SalesPlanTypeEnum.PLAN_FOURTEEN.getType())) {
                    if (!ChannelTypeEnum.CLOUD_BUSINESS.getCode().equals(channelCodeList.get(0))) {
                        throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                    }
                    operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_FOURTEEN.getDesc());
                    channelName = ChannelTypeEnum.CLOUD_BUSINESS.getDesc();
                }
                //APP
                else if (type.equals(SalesPlanTypeEnum.PLAN_TWELVE.getType())) {
                    if (!ChannelTypeEnum.APP.getCode().equals(channelCodeList.get(0))) {
                        throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                    }
                    operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_TWELVE.getDesc());
                    channelName = ChannelTypeEnum.APP.getDesc();
                }
                //经销中心
                else {
                    if (!ChannelTypeEnum.DEALER.getCode().equals(channelCodeList.get(0))) {
                        throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                    }
                    operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_THIRTEEN.getDesc());
                    channelName = ChannelTypeEnum.DEALER.getDesc();
                }
                //表格数据转换为DTO集合
                dtoList = this.getDtoLists(salesOtherReadList, type, channelName, skus, categorys, provinceList, cityNameList
                        , storeList, provinceListByStore, cityListByStore, countyListByStore, provinceNameListByCity, skuUnitList);
            }
            //可能会有重复数据，渠道计划类型唯一，销售计划（加盟）根据时间、商品、门店，经销中心根据省份、城市、区， 其他根据时间、商品
            dtoList.parallelStream().collect(Collectors.groupingBy(o -> (o.getPlanStartDate() + o.getSkuCode() + (ObjectUtil.isNotNull(o.getStoreCode()) ? o.getStoreCode() : "") + (ObjectUtil.isNotNull(o.getProvinceCode()) ? o.getProvinceCode() : "") + (ObjectUtil.isNotNull(o.getCityCode()) ? o.getCityCode() : "") + (ObjectUtil.isNotNull(o.getCountyCode()) ? o.getCountyCode() : "")), Collectors.toList())).forEach((k, v) -> {
                BigDecimal reduce = v.stream().map(SalesPlanOtherDTO::getPlanQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                Long id = idWorker.getId();
                v.get(0).setPlanQty(reduce);
                v.get(0).setChannelConfirmedQty(reduce);
                v.get(0).setSalesPlanOtherNo(id + "");
                v.get(0).setOpSign(identification + "");
                //v.get(0).setPlanImportDate(new Date());
                salesOtherList.add(v.get(0));
            });
        } else {
            if (SalesPlanTypeEnum.PLAN_FIFTEEN.getType().equals(type)) {
                //新开店导入
                impType = 2;
                operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_FIFTEEN.getDesc());
                salesOtherReadList.forEach(item -> {
                    //校验数据
                    checkOtherData(item, CommonConstants.TWO);
                });
                //获取所有省份为江苏省的数据
                List<SalesReadOtherDTO> simpleList = salesOtherReadList.stream().filter(item -> CommonConstants.PRO_NAME.contains(item.getProvinceName())).distinct().collect(Collectors.toList());
                simpleList.forEach(item -> {
                    //省份为江苏省，城市不能为空
                    if (ObjectUtil.isNull(item.getCityName())) {
                        throw new RomeException(ResponseMsg.PARAM_ERROR_2009.getCode(), ResponseMsg.PARAM_ERROR_2009.getMsg());
                    }
                });
                //获取导入数据中去重后的商品code集合
                List<String> skuCodeList = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getSkuCode())).map(SalesReadOtherDTO::getSkuCode).distinct().collect(Collectors.toList());
                List<SkuUnitExtDTO> skuUnitList = itemCoreFacade.getSkuUnitByCodeAndType(skuCodeList, 5);
                ifTrue = skuUnitList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuUnitList.stream().map(SkuUnitExtDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2033.getCode(), ResponseMsg.FAIL_2033.getMsg() + list);
                }
                /*List<SkuPurchasePermitDTO> skuPurchaseList = categoryFacade.querySkuPermit(skuCodeList);
                ifTrue = skuPurchaseList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuPurchaseList.stream().map(SkuPurchasePermitDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.PARAM_ERROR_2006.getCode(), ResponseMsg.PARAM_ERROR_2006.getMsg() + "，编码为：" + list);
                }
                List<String> permitList = new ArrayList<>();
                skuPurchaseList.forEach(e -> {
                    //如果商品编码不是当前渠道可下单商品
                    if (!e.getPermit()) {
                        permitList.add(e.getSkuCode());
                    }
                });
                if (permitList.size() > 0) {
                    throw new RomeException(ResponseMsg.PARAM_ERROR_2007.getCode(), ResponseMsg.PARAM_ERROR_2007.getMsg() + "，错误编码为：" + permitList);
                }*/
                //根据商品code集合获取商品对应品类id集合(接口最多一次只能调100个)
                List<SkuInfoDTO> skus = new ArrayList<>();
                int perThreadHandleCount = 100;
                int countNum = 0;
                while (countNum < skuCodeList.size()) {
                    countNum += perThreadHandleCount;
                    List<String> dtos = ImmutableList.copyOf(skuCodeList.subList(countNum - perThreadHandleCount,
                            countNum < skuCodeList.size() ? countNum : skuCodeList.size()));
                    List<SkuInfoDTO> skuInfos = itemCoreFacade.getAllCategoryIdBySkuCode(1, dtos.size(), dtos).getList();
                    skus.addAll(skuInfos);
                }
                ifTrue = skus.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skus.stream().map(SkuInfoDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2032.getCode(), ResponseMsg.FAIL_2032.getMsg() + list);
                }
                List<Integer> ids = skus.stream().filter(f -> ObjectUtil.isNotNull(f.getCategoryId())).map(SkuInfoDTO::getCategoryId).distinct().collect(Collectors.toList());
                //查询出所有商品code对应的品类信息
                List<CategorySimpleDTO> categorys = itemCoreFacade.getAllCategoryByCategoryId(ids);

                //获取所有不重复省份的名称
                List<String> provinceNams = salesOtherReadList.stream().map(SalesReadOtherDTO::getProvinceName).distinct().collect(Collectors.toList());
                provinceList = baseDataFacade.listProvinceByList(provinceNams);
                ifTrue = provinceList.size() == provinceNams.size();
                if (!ifTrue) {
                    List<String> proSt = provinceList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                    List<String> list = provinceNams.stream().filter(item -> !proSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + list);
                }
                //获取所有不重复城市的名称
                List<String> cityNames = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName())).map(SalesReadOtherDTO::getCityName).distinct().collect(Collectors.toList());
                if (cityNames.size() > 0) {
                    //根据城市名称获取城市信息
                    cityNameList = baseDataFacade.listProvinceByList(cityNames);
                    ifTrue = cityNameList.size() == cityNames.size();
                    if (!ifTrue) {
                        List<String> citySt = cityNameList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                        List<String> list = cityNames.stream().filter(item -> !citySt.contains(item)).collect(Collectors.toList());
                        throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + list);
                    }
                    //获取省份编码
                    List<String> provinces = cityNameList.stream().map(AreaDTO::getParentCode).collect(Collectors.toList());
                    if (provinces.size() > 0) {
                        provinceNameListByCity = baseDataFacade.listAreaInfoByCode(provinces);
                    }
                }

                dtoList = this.getNewStoreList(salesOtherReadList, skus, categorys, provinceList, cityNameList
                        , provinceNameListByCity, skuUnitList);
                dtoList.parallelStream().collect(Collectors.groupingBy(o -> (o.getPlanStartDate() + o.getSkuCode() + o.getChannelCode() + o.getType() + (ObjectUtil.isNotNull(o.getProvinceCode()) ? o.getProvinceCode() : "") + (ObjectUtil.isNotNull(o.getCityCode()) ? o.getCityCode() : "") + (ObjectUtil.isNotNull(o.getCountyCode()) ? o.getCountyCode() : "")), Collectors.toList())).forEach((k, v) -> {
                    Long id = idWorker.getId();
                    //优惠券不添加到总量里
                    if (v.get(0).getSkuName().contains("优惠券")) {
                        BigDecimal qty = v.stream().map(SalesPlanOtherDTO::getCouponQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                        v.get(0).setCouponQty(qty);
                    } else {
                        BigDecimal reduce = v.stream().map(SalesPlanOtherDTO::getChannelConfirmedQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                        v.get(0).setChannelConfirmedQty(reduce);
                        v.get(0).setAllchannelConfirmedQty(reduce);
                        v.get(0).setPlanQty(reduce);
                    }
                    v.get(0).setSalesPlanOtherNo(id + "");
                    //v.get(0).setOpSign(identification + "");
                    //v.get(0).setPlanImportDate(new Date());
                    salesOtherList.add(v.get(0));
                });
            } else {
                //新品铺货导入
                impType = 3;
                operationDto.setOpContent("导入" + SalesPlanTypeEnum.PLAN_SIXTEEN.getDesc());
                salesReadList.forEach(item -> {
                    //校验数据
                    checkData(item, CommonConstants.TWO);
                });
                //获取所有省份为江苏省的数据
                List<SalesReadDTO> simpleList = salesReadList.stream().filter(item -> CommonConstants.PRO_NAME.contains(item.getProvinceName())).distinct().collect(Collectors.toList());
                simpleList.forEach(item -> {
                    //省份为江苏省，城市不能为空
                    if (ObjectUtil.isNull(item.getCityName())) {
                        throw new RomeException(ResponseMsg.PARAM_ERROR_2009.getCode(), ResponseMsg.PARAM_ERROR_2009.getMsg());
                    }
                });
                //判断表格填入渠道编码是否正确（最多只能导入5种）
                //获取导入数据中去重的销售渠道编码集合
                List<String> channelCodeList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getChannelCode())).map(SalesReadDTO::getChannelCode).distinct().collect(Collectors.toList());
                List<String> channelNum = new ArrayList<>();
                if (channelCodeList.size() < 6) {
                    for (String name : channelCodeList) {
                        if (name.equals(ChannelTypeEnum.DIRECTLY_OPERATE.getCode()) || name.equals(ChannelTypeEnum.JOIN_IN.getCode()) || name.equals(ChannelTypeEnum.CLOUD_BUSINESS.getCode())
                                || name.equals(ChannelTypeEnum.APP.getCode()) || name.equals(ChannelTypeEnum.DEALER.getCode())) {
                            channelNum.add(name);
                        }
                    }
                } else {
                    throw new RomeException(ResponseMsg.FAIL_2030.getCode(), ResponseMsg.FAIL_2030.getMsg());
                }
                if (channelCodeList.size() != channelNum.size()) {
                    throw new RomeException(ResponseMsg.FAIL_2031.getCode(), ResponseMsg.FAIL_2031.getMsg());
                }
                //获取导入数据中去重后的商品code集合
                List<String> skuCodeList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getSkuCode())).map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                //转换为基础单位
                List<SkuUnitExtDTO> skuUnitList = itemCoreFacade.getSkuUnitByCodeAndType(skuCodeList, 5);
                ifTrue = skuUnitList.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skuUnitList.stream().map(SkuUnitExtDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2033.getCode(), ResponseMsg.FAIL_2033.getMsg() + list);
                }
                //根据商品code集合获取商品对应品类id集合(接口最多一次只能调100个)
                List<SkuInfoDTO> skus = new ArrayList<>();
                int perThreadHandleCount = 100;
                int countNum = 0;
                while (countNum < skuCodeList.size()) {
                    countNum += perThreadHandleCount;
                    List<String> dtos = ImmutableList.copyOf(skuCodeList.subList(countNum - perThreadHandleCount,
                            countNum < skuCodeList.size() ? countNum : skuCodeList.size()));
                    List<SkuInfoDTO> skuInfos = itemCoreFacade.getAllCategoryIdBySkuCode(1, dtos.size(), dtos).getList();
                    skus.addAll(skuInfos);
                }
                ifTrue = skus.size() == skuCodeList.size();
                if (!ifTrue) {
                    List<String> skuSt = skus.stream().map(SkuInfoDTO::getSkuCode).collect(Collectors.toList());
                    List<String> list = skuCodeList.stream().filter(item -> !skuSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2032.getCode(), ResponseMsg.FAIL_2032.getMsg() + list);
                }
                List<Integer> ids = skus.stream().filter(f -> ObjectUtil.isNotNull(f.getCategoryId())).map(SkuInfoDTO::getCategoryId).distinct().collect(Collectors.toList());
                //查询出所有商品code对应的品类信息
                List<CategorySimpleDTO> categorys = itemCoreFacade.getAllCategoryByCategoryId(ids);
                //获取所有不重复省份的名称
                List<String> provinceNams = salesReadList.stream().map(SalesReadDTO::getProvinceName).distinct().collect(Collectors.toList());
                provinceList = baseDataFacade.listProvinceByList(provinceNams);
                ifTrue = provinceList.size() == provinceNams.size();
                if (!ifTrue) {
                    List<String> proSt = provinceList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                    List<String> list = provinceNams.stream().filter(item -> !proSt.contains(item)).collect(Collectors.toList());
                    throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + list);
                }
                //获取所有不重复城市的名称
                List<String> cityNames = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName())).map(SalesReadDTO::getCityName).distinct().collect(Collectors.toList());
                if (cityNames.size() > 0) {
                    //根据城市名称获取城市信息
                    cityNameList = baseDataFacade.listProvinceByList(cityNames);
                    ifTrue = cityNameList.size() == cityNames.size();
                    if (!ifTrue) {
                        List<String> citySt = cityNameList.stream().map(AreaDTO::getName).collect(Collectors.toList());
                        List<String> list = cityNames.stream().filter(item -> !citySt.contains(item)).collect(Collectors.toList());
                        throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + list);
                    }
                    //获取省份编码
                    List<String> provinces = cityNameList.stream().map(AreaDTO::getParentCode).collect(Collectors.toList());
                    if (provinces.size() > 0) {
                        provinceNameListByCity = baseDataFacade.listAreaInfoByCode(provinces);
                    }
                }
                //加盟、直营
                if (channelCodeList.contains(ChannelTypeEnum.DIRECTLY_OPERATE.getCode()) || channelCodeList.contains(ChannelTypeEnum.JOIN_IN.getCode())) {
                    //checkChannelSkuPermit(salesReadList, null, CommonConstants.ZERO);

                    //获取表格中所有有门店的数据
                    List<SalesReadDTO> stores = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getStoreCode())).distinct().collect(Collectors.toList());
                    if (stores.size() > 0) {
                        List<String> storeCodes = stores.stream().map(SalesReadDTO::getStoreCode).distinct().collect(Collectors.toList());
                        //获取基础服务中心所有门店
                        storeList = baseDataFacade.listStore(new StoreDTO()).getList();
                        //筛选出表格中的门店
                        storeList = storeList.stream().filter(f -> storeCodes.contains(f.getCode())).collect(Collectors.toList());
                        List<String> stos = storeList.stream().map(StoreDTO::getCode).collect(Collectors.toList());
                        List<String> noStoreList = storeCodes.stream().filter(item -> !stos.contains(item)).collect(Collectors.toList());
                        if (noStoreList.size() > 0) {
                            throw new RomeException(ResponseMsg.FAIL_2013.getCode(), ResponseMsg.FAIL_2013.getMsg() + ",错误门店code：" + noStoreList);
                        }
                        List<String> failDirectlyList = new ArrayList<>();
                        List<String> failJoinList = new ArrayList<>();
                        for (SalesReadDTO readDto : salesReadList) {
                            if (ObjectUtil.isNotNull(readDto.getStoreCode())) {
                                String channel = readDto.getChannelCode();
                                List<StoreDTO> storess = storeList.stream().filter(item -> item.getCode().equals(readDto.getStoreCode())).collect(Collectors.toList());
                                //如果为直营
                                if (channel.equals(ChannelTypeEnum.DIRECTLY_OPERATE.getCode())) {
                                    if (!storess.get(0).getStoreProperties().equals(ShopTypeEnum.DIRECTLY_SHOP.getStoreProperties()) && !storess.get(0).getStoreProperties().equals(ShopTypeEnum.NON_BRANCH_SHOP.getStoreProperties()) && !storess.get(0).getStoreProperties().equals(ShopTypeEnum.POOL_SHOP.getStoreProperties())) {
                                        failDirectlyList.add(readDto.getChannelCode() + "-" + readDto.getStoreCode());
                                    }
                                } else {
                                    if (!storess.get(0).getStoreProperties().equals(ShopTypeEnum.JOIN_SHOP.getStoreProperties()) && !storess.get(0).getStoreProperties().equals(ShopTypeEnum.JOIN_TRUSTEESHIP_SHOP.getStoreProperties())) {
                                        failJoinList.add(readDto.getChannelCode() + "-" + readDto.getStoreCode());
                                    }
                                }
                            }
                        }
                        if (failDirectlyList.size() > 0) {
                            throw new RomeException(ResponseMsg.FAIL_2905.getCode(), ResponseMsg.FAIL_2905.getMsg() + failDirectlyList);
                        }
                        if (failJoinList.size() > 0) {
                            throw new RomeException(ResponseMsg.FAIL_2906.getCode(), ResponseMsg.FAIL_2906.getMsg() + failJoinList);
                        }
                        //获取不重复
                        List<String> provinceCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getProvinceCode())).map(StoreDTO::getProvinceCode).distinct().collect(Collectors.toList());
                        List<String> cityCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getCityCode())).map(StoreDTO::getCityCode).distinct().collect(Collectors.toList());
                        List<String> countyCodes = storeList.stream().filter(f -> ObjectUtil.isNotNull(f.getAreaCode())).map(StoreDTO::getAreaCode).distinct().collect(Collectors.toList());
                        //根据code批量获取省市区信息
                        if (provinceCodes.size() > 0) {
                            provinceListByStore = baseDataFacade.listAreaInfoByCode(provinceCodes);
                        }
                        //需要校验从接口获取数据是否正确
                        if (cityCodes.size() > 0) {
                            cityListByStore = baseDataFacade.listAreaInfoByCode(cityCodes);
                        }
                        if (countyCodes.size() > 0) {
                            countyListByStore = baseDataFacade.listAreaInfoByCode(countyCodes);
                        }
                    }
                } else {
                    //checkChannelSkuPermit(salesReadList, null, CommonConstants.ONE);
                }
                dtoList = this.getNewProductList(salesReadList, skus, categorys, provinceList, cityNameList, storeList,
                        provinceListByStore, cityListByStore, countyListByStore,
                        provinceNameListByCity, skuUnitList);

                dtoList.parallelStream().collect(Collectors.groupingBy(o -> (o.getPlanStartDate() + o.getSkuCode() + o.getChannelCode() + o.getType() + (ObjectUtil.isNotNull(o.getStoreCode()) ? o.getStoreCode() : "") + (ObjectUtil.isNotNull(o.getProvinceCode()) ? o.getProvinceCode() : "") + (ObjectUtil.isNotNull(o.getCityCode()) ? o.getCityCode() : "") + (ObjectUtil.isNotNull(o.getCountyCode()) ? o.getCountyCode() : "")), Collectors.toList())).forEach((k, v) -> {
                    BigDecimal reduce = v.stream().map(SalesPlanOtherDTO::getChannelConfirmedQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                    Long id = idWorker.getId();
                    v.get(0).setSalesPlanOtherNo(id + "");
                    v.get(0).setPlanQty(reduce);
                    v.get(0).setChannelConfirmedQty(reduce);
                    v.get(0).setAllchannelConfirmedQty(reduce);
                    //v.get(0).setOpSign(identification + "");
                    //v.get(0).setPlanImportDate(new Date());
                    salesOtherList.add(v.get(0));
                });
            }
        }
        operationDto.setOpAmount(new Long((long) salesOtherList.size()));
        //新增操作日志表
        OperationLogRecordDTO recordDto = operationLogRecordFacade.insertOperationLog(operationDto);
        //校验通过，异步导入数据
        startImportPlan(salesOtherList, impType, recordDto.getId());
        //导入统一返回处理中，查看任务列表查询状态
        return OperationStatusEnum.PROCESSING.getType();
    }

    /**
     * 更新确认量
     *
     * @param all
     * @param unitType
     */
    @Override
    public Boolean confirm(List<SalesPlanOtherDTO> all, Long unitType) {
        Integer level = getOtherPlanLevel();
        return salesPlanOtherFacade.confirm(all, unitType, level);
    }


    /**
     * 表格数据转换为实体类集合(销售计划加盟)
     *
     * @param salesOtherReadList     表格数据集合
     * @param type                   类型
     * @param channelName            渠道名称
     * @param skus                   编码集合
     * @param categorys              品类集合
     * @param cityNameList           需要拆分的城市集合
     * @param storeList              门店集合
     * @param provinceListByStore    门店对应的省份名称集合
     * @param cityListByStore        门店对应的城市名称集合
     * @param countyListByStore      门店对应的县/区名称集合
     * @param provinceNameListByCity 城市对应所有门店对应的省名称集合
     * @param skuUnitList            商品单位信息集合
     * @return
     */
    public List<SalesPlanOtherDTO> getDtoList(List<SalesReadDTO> salesOtherReadList, String type, String channelName, List<SkuInfoDTO> skus, List<CategorySimpleDTO> categorys, List<AreaDTO> provinceList, List<AreaDTO> cityNameList, List<StoreDTO> storeList, List<AreaDTO> provinceListByStore, List<AreaDTO> cityListByStore, List<AreaDTO> countyListByStore, List<AreaDTO> provinceNameListByCity, List<SkuUnitExtDTO> skuUnitList) {
        List<SalesPlanOtherDTO> dtoList = new ArrayList<>();
        //获取当前时间开始往后5周日期
        //List<Map<String, Date>> dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
        //测试设置获取导入周的时间
        List<String> time = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getTime())).map(SalesReadDTO::getTime).collect(Collectors.toList());
        List<Map<String, Date>> dateMap;
        Date importDate;
        if (CollectionUtil.isEmpty(time)) {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
            importDate = new Date();
        } else {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(DateUtil.parseDate(time.get(0)), CommonConstants.SIX);
            importDate = DateUtil.parseDate(time.get(0));
        }
        for (SalesReadDTO readDto : salesOtherReadList) {
            int i = 0;
            for (Map<String, Date> week : dateMap) {
                i++;
                if (i == 1) {
                    continue;
                }
                SalesPlanOtherDTO dto = new SalesPlanOtherDTO();
                dto.setPlanImportDate(importDate);
                //当前周不用处理，直接处理当前周往后周的数据
                if (i == 2) {
                    dto.setPlanQty(new BigDecimal(readDto.getWeekTwoNum()));
                } else if (i == 3) {
                    dto.setPlanQty(new BigDecimal(readDto.getWeekThreeNum()));
                } else if (i == 4) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekFourNum()) ? new BigDecimal(readDto.getWeekFourNum()) : BigDecimal.ZERO);
                } else if (i == 5) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekFiveNum()) ? new BigDecimal(readDto.getWeekFiveNum()) : BigDecimal.ZERO);
                } else if (i == 6) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekSixNum()) ? new BigDecimal(readDto.getWeekSixNum()) : BigDecimal.ZERO);
                } else {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekSevenNum()) ? new BigDecimal(readDto.getWeekSevenNum()) : BigDecimal.ZERO);
                }
                dto.setPlanStartDate(week.get("startTime"));
                dto.setPlanEndDate(week.get("endTime"));
                dto.setType(type);
                //默认未确认
                dto.setStatus(SalesConfirmStatusEnum.UNCONFIRMED.getType());
                dto.setChannelCode(readDto.getChannelCode());
                dto.setChannelName(channelName);

                if (ObjectUtil.isNotNull(readDto.getStoreCode())) {
                    List<StoreDTO> stores = storeList.stream().filter(store -> store.getCode().equals(readDto.getStoreCode())).collect(Collectors.toList());
                    //如果填了门店
                    if (stores.size() > 0) {
                        dto.setStoreCode(stores.get(0).getCode());
                        dto.setStoreName(stores.get(0).getName());
                        String provinceCode = stores.get(0).getProvinceCode();
                        String cityCode = stores.get(0).getCityCode();
                        String countCode = stores.get(0).getAreaCode();
                        //匹配对应的省市区
                        List<AreaDTO> proList = provinceListByStore.stream().filter(pro -> pro.getCode().equals(provinceCode)).collect(Collectors.toList());
                        List<AreaDTO> cityList = cityListByStore.stream().filter(pro -> pro.getCode().equals(cityCode)).collect(Collectors.toList());
                        List<AreaDTO> countList = countyListByStore.stream().filter(pro -> pro.getCode().equals(countCode)).collect(Collectors.toList());
                        if (proList.size() > 0) {
                            dto.setProvinceCode(proList.get(0).getCode());
                            dto.setProvinceName(proList.get(0).getName());
                        }
                        if (cityList.size() > 0) {
                            dto.setCityCode(cityList.get(0).getCode());
                            dto.setCityName(cityList.get(0).getName());
                        }
                        if (countList.size() > 0) {
                            dto.setCountyCode(countList.get(0).getCode());
                            dto.setCountyName(countList.get(0).getName());
                        }
                    }
                }
                //如果填了城市
                List<AreaDTO> city = cityNameList.stream().filter(pro -> ObjectUtil.isNotNull(readDto.getCityName()) && pro.getName().contains(readDto.getCityName())).collect(Collectors.toList());
                if (city.size() > 0) {
                    if (provinceNameListByCity.size() > 0) {
                        List<AreaDTO> province = provinceNameListByCity.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                        if (province.size() > 0) {
                            dto.setProvinceCode(province.get(0).getCode());
                            dto.setProvinceName(province.get(0).getName());
                        }
                    }
                    dto.setCityCode(city.get(0).getCode());
                    dto.setCityName(city.get(0).getName());
                } else {
                    //省份必填(填了城市取城市)
                    List<AreaDTO> province = provinceList.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                    if (province.size() > 0) {
                        dto.setProvinceCode(province.get(0).getCode());
                        dto.setProvinceName(province.get(0).getName());
                    }
                }

                List<SkuInfoDTO> skuInfo = skus.stream().filter(sku -> sku.getSkuCode().equals(readDto.getSkuCode())).collect(Collectors.toList());
                if (skuInfo.size() > 0) {
                    List<CategorySimpleDTO> category = categorys.stream().filter(ter -> ter.getId().equals(skuInfo.get(0).getCategoryId())).collect(Collectors.toList());
                    if (category.size() > 0) {
                        category.get(0).getParentCategoryDTOList().forEach(cate -> {
                            if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_ONE)) {
                                dto.setPriCategoryCode(cate.getCategoryCode().toString());
                                dto.setPriCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_TWO)) {
                                dto.setSecCategoryCode(cate.getCategoryCode().toString());
                                dto.setSecCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_THREE)) {
                                dto.setTerCategoryCode(cate.getCategoryCode().toString());
                                dto.setTerCategoryName(cate.getCategoryName());
                            }
                        });
                    }
                    List<SkuUnitExtDTO> units = skuUnitList.stream().filter(ter -> ter.getSkuCode().equals(skuInfo.get(0).getSkuCode())).collect(Collectors.toList());
                    if (units.size() > 0) {
                        dto.setUnitCode(units.get(0).getUnitCode());
                        dto.setUnitName(units.get(0).getUnitName());
                    }
                    dto.setSkuCode(skuInfo.get(0).getSkuCode());
                    dto.setSkuName(skuInfo.get(0).getSkuName());
                }
                dto.setCreator(UserContext.getUserId());
                dto.setCreatorName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dto.setModifier(UserContext.getUserId());
                dto.setModifierName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dtoList.add(dto);
            }
        }
        return dtoList;
    }

    /**
     * 表格数据转换为实体类集合(销售计划(APP、云商、经销中心))
     *
     * @param salesOtherReadList     表格数据集合
     * @param type                   类型
     * @param channelName            渠道名称
     * @param skus                   编码集合
     * @param categorys              品类集合
     * @param cityNameList           需要拆分的城市集合
     * @param storeList              门店集合
     * @param provinceListByStore    门店对应的省份名称集合
     * @param cityListByStore        门店对应的城市名称集合
     * @param countyListByStore      门店对应的县/区名称集合
     * @param provinceNameListByCity 城市对应所有门店对应的省名称集合
     * @param skuUnitList            商品单位信息集合
     * @return
     */
    public List<SalesPlanOtherDTO> getDtoLists(List<SalesReadOtherDTO> salesOtherReadList, String type, String channelName, List<SkuInfoDTO> skus, List<CategorySimpleDTO> categorys, List<AreaDTO> provinceList, List<AreaDTO> cityNameList, List<StoreDTO> storeList, List<AreaDTO> provinceListByStore, List<AreaDTO> cityListByStore, List<AreaDTO> countyListByStore, List<AreaDTO> provinceNameListByCity, List<SkuUnitExtDTO> skuUnitList) {
        List<SalesPlanOtherDTO> dtoList = new ArrayList<>();
        //获取当前时间开始往后5周日期
        //List<Map<String, Date>> dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);

        //测试设置获取导入周的时间
        List<String> time = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getTime())).map(SalesReadOtherDTO::getTime).collect(Collectors.toList());
        List<Map<String, Date>> dateMap;
        Date importDate;
        if (CollectionUtil.isEmpty(time)) {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
            importDate = new Date();
        } else {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(DateUtil.parseDate(time.get(0)), CommonConstants.SIX);
            importDate = DateUtil.parseDate(time.get(0));
        }

        for (SalesReadOtherDTO readDto : salesOtherReadList) {
            int i = 0;
            for (Map<String, Date> week : dateMap) {
                i++;
                if (i == 1) {
                    continue;
                }
                SalesPlanOtherDTO dto = new SalesPlanOtherDTO();
                dto.setPlanImportDate(importDate);
                //当前周不用处理，直接处理当前周往后周的数据
                if (i == 2) {
                    dto.setPlanQty(new BigDecimal(readDto.getWeekTwoNum()));
                } else if (i == 3) {
                    dto.setPlanQty(new BigDecimal(readDto.getWeekThreeNum()));
                } else if (i == 4) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekFourNum()) ? new BigDecimal(readDto.getWeekFourNum()) : BigDecimal.ZERO);
                } else if (i == 5) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekFiveNum()) ? new BigDecimal(readDto.getWeekFiveNum()) : BigDecimal.ZERO);
                } else if (i == 6) {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekSixNum()) ? new BigDecimal(readDto.getWeekSixNum()) : BigDecimal.ZERO);
                } else {
                    dto.setPlanQty(ObjectUtil.isNotNull(readDto.getWeekSevenNum()) ? new BigDecimal(readDto.getWeekSevenNum()) : BigDecimal.ZERO);
                }
                dto.setPlanStartDate(week.get("startTime"));
                dto.setPlanEndDate(week.get("endTime"));
                dto.setType(type);
                //默认未确认
                dto.setStatus(SalesConfirmStatusEnum.UNCONFIRMED.getType());
                dto.setChannelCode(readDto.getChannelCode());
                dto.setChannelName(channelName);
                //如果填了城市
                List<AreaDTO> city = cityNameList.stream().filter(pro -> ObjectUtil.isNotNull(readDto.getCityName()) && pro.getName().contains(readDto.getCityName())).collect(Collectors.toList());
                if (city.size() > 0) {
                    if (provinceNameListByCity.size() > 0) {
                        List<AreaDTO> province = provinceNameListByCity.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                        if (province.size() > 0) {
                            dto.setProvinceCode(province.get(0).getCode());
                            dto.setProvinceName(province.get(0).getName());
                        }
                    }
                    dto.setCityCode(city.get(0).getCode());
                    dto.setCityName(city.get(0).getName());
                } else {
                    //省份必填(填了城市取城市)
                    List<AreaDTO> province = provinceList.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                    if (province.size() > 0) {
                        dto.setProvinceCode(province.get(0).getCode());
                        dto.setProvinceName(province.get(0).getName());
                    }
                }

                List<SkuInfoDTO> skuInfo = skus.stream().filter(sku -> sku.getSkuCode().equals(readDto.getSkuCode())).collect(Collectors.toList());
                if (skuInfo.size() > 0) {
                    List<CategorySimpleDTO> category = categorys.stream().filter(ter -> ter.getId().equals(skuInfo.get(0).getCategoryId())).collect(Collectors.toList());
                    if (category.size() > 0) {
                        category.get(0).getParentCategoryDTOList().forEach(cate -> {
                            if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_ONE)) {
                                dto.setPriCategoryCode(cate.getCategoryCode().toString());
                                dto.setPriCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_TWO)) {
                                dto.setSecCategoryCode(cate.getCategoryCode().toString());
                                dto.setSecCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_THREE)) {
                                dto.setTerCategoryCode(cate.getCategoryCode().toString());
                                dto.setTerCategoryName(cate.getCategoryName());
                            }
                        });
                    }
                    List<SkuUnitExtDTO> units = skuUnitList.stream().filter(ter -> ter.getSkuCode().equals(skuInfo.get(0).getSkuCode())).collect(Collectors.toList());
                    if (units.size() > 0) {
                        dto.setUnitCode(units.get(0).getUnitCode());
                        dto.setUnitName(units.get(0).getUnitName());
                    }
                    dto.setSkuCode(skuInfo.get(0).getSkuCode());
                    dto.setSkuName(skuInfo.get(0).getSkuName());
                }
                dto.setCreator(UserContext.getUserId());
                dto.setCreatorName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dto.setModifier(UserContext.getUserId());
                dto.setModifierName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dtoList.add(dto);
            }
        }
        return dtoList;
    }


    /**
     * 表格数据转换为实体类集合(新品铺货计划)
     *
     * @param skus                   编码集合
     * @param categorys              品类集合
     * @param cityNameList           需要拆分的城市集合
     * @param storeList              门店集合
     * @param provinceListByStore    门店对应的省份名称集合
     * @param cityListByStore        门店对应的城市名称集合
     * @param countyListByStore      门店对应的县/区名称集合
     * @param provinceNameListByCity 城市对应所有门店对应的省名称集合
     * @param skuUnitList            商品单位信息集合
     * @return
     */
    public List<SalesPlanOtherDTO> getNewProductList(List<SalesReadDTO> salesReadList, List<SkuInfoDTO> skus, List<CategorySimpleDTO> categorys, List<AreaDTO> provinceList, List<AreaDTO> cityNameList, List<StoreDTO> storeList, List<AreaDTO> provinceListByStore, List<AreaDTO> cityListByStore, List<AreaDTO> countyListByStore, List<AreaDTO> provinceNameListByCity, List<SkuUnitExtDTO> skuUnitList) {
        List<SalesPlanOtherDTO> dtoList = new ArrayList<>();
        //获取当前时间开始往后5周日期
        //List<Map<String, Date>> dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
        //测试设置获取导入周的时间
        List<String> time = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getTime())).map(SalesReadDTO::getTime).collect(Collectors.toList());
        List<Map<String, Date>> dateMap;
        Date importDate;
        if (CollectionUtil.isEmpty(time)) {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
            importDate = new Date();
        } else {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(DateUtil.parseDate(time.get(0)), CommonConstants.SIX);
            importDate = DateUtil.parseDate(time.get(0));
        }
        for (SalesReadDTO readDto : salesReadList) {
            int i = 0;
            for (Map<String, Date> week : dateMap) {
                i++;
                if (i == 1) {
                    continue;
                }
                SalesPlanOtherDTO dto = new SalesPlanOtherDTO();
                dto.setPlanImportDate(importDate);
                //当前周不用处理，直接处理当前周往后周的数据
                if (i == 2) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekTwoNum()));
                } else if (i == 3) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekThreeNum()));
                } else if (i == 4) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekFourNum()));
                } else if (i == 5) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekFiveNum()));
                } else if (i == 6) {
                    dto.setChannelConfirmedQty(ObjectUtil.isNotNull(readDto.getWeekSixNum()) ? new BigDecimal(readDto.getWeekSixNum()) : BigDecimal.ZERO);
                } else {
                    dto.setChannelConfirmedQty(ObjectUtil.isNotNull(readDto.getWeekSevenNum()) ? new BigDecimal(readDto.getWeekSevenNum()) : BigDecimal.ZERO);
                }
                dto.setPlanStartDate(week.get("startTime"));
                dto.setPlanEndDate(week.get("endTime"));
                //同步为已确认
                dto.setStatus(SalesConfirmStatusEnum.CONFIRMED.getType());
                dto.setCreator(UserContext.getUserId());
                dto.setCreatorName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dto.setModifier(UserContext.getUserId());
                dto.setModifierName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                //直营、加盟
                if (readDto.getChannelCode().equals(ChannelTypeEnum.DIRECTLY_OPERATE.getCode()) || readDto.getChannelCode().equals(ChannelTypeEnum.JOIN_IN.getCode())) {
                    String channelName = "";
                    String type = "";
                    //直营
                    if (ChannelTypeEnum.DIRECTLY_OPERATE.getCode().equals(readDto.getChannelCode())) {
                        channelName = ChannelTypeEnum.DIRECTLY_OPERATE.getDesc();
                        type = SalesOtherTypeEnum.PLAN_SEVEN.getType();
                    } else {
                        channelName = ChannelTypeEnum.JOIN_IN.getDesc();
                        type = SalesOtherTypeEnum.PLAN_FIFTEEN.getType();
                    }

                    if (ObjectUtil.isNotNull(readDto.getStoreCode())) {
                        List<StoreDTO> stores = storeList.stream().filter(store -> store.getCode().equals(readDto.getStoreCode())).collect(Collectors.toList());
                        //如果填了门店
                        if (stores.size() > 0) {
                            dto.setStoreCode(stores.get(0).getCode());
                            dto.setStoreName(stores.get(0).getName());
                            String provinceCode = stores.get(0).getProvinceCode();
                            String cityCode = stores.get(0).getCityCode();
                            String countCode = stores.get(0).getAreaCode();
                            //匹配对应的省市区
                            List<AreaDTO> proList = provinceListByStore.stream().filter(pro -> pro.getCode().equals(provinceCode)).collect(Collectors.toList());
                            List<AreaDTO> cityList = cityListByStore.stream().filter(pro -> pro.getCode().equals(cityCode)).collect(Collectors.toList());
                            List<AreaDTO> countList = countyListByStore.stream().filter(pro -> pro.getCode().equals(countCode)).collect(Collectors.toList());
                            if (proList.size() > 0) {
                                dto.setProvinceCode(proList.get(0).getCode());
                                dto.setProvinceName(proList.get(0).getName());
                            }
                            if (cityList.size() > 0) {
                                dto.setCityCode(cityList.get(0).getCode());
                                dto.setCityName(cityList.get(0).getName());
                            }
                            if (countList.size() > 0) {
                                dto.setCountyCode(countList.get(0).getCode());
                                dto.setCountyName(countList.get(0).getName());
                            }
                        }
                    }
                    //如果填了城市
                    List<AreaDTO> city = cityNameList.stream().filter(pro -> ObjectUtil.isNotNull(readDto.getCityName()) && pro.getName().contains(readDto.getCityName())).collect(Collectors.toList());
                    if (city.size() > 0) {
                        if (provinceNameListByCity.size() > 0) {
                            List<AreaDTO> province = provinceNameListByCity.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                            if (province.size() > 0) {
                                dto.setProvinceCode(province.get(0).getCode());
                                dto.setProvinceName(province.get(0).getName());
                            }
                        }
                        dto.setCityCode(city.get(0).getCode());
                        dto.setCityName(city.get(0).getName());
                    } else {
                        //省份必填(填了城市取城市)
                        List<AreaDTO> province = provinceList.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                        if (province.size() > 0) {
                            dto.setProvinceCode(province.get(0).getCode());
                            dto.setProvinceName(province.get(0).getName());
                        }
                    }
                    List<SkuInfoDTO> skuInfo = skus.stream().filter(sku -> sku.getSkuCode().equals(readDto.getSkuCode())).collect(Collectors.toList());
                    if (skuInfo.size() > 0) {
                        List<CategorySimpleDTO> category = categorys.stream().filter(ter -> ter.getId().equals(skuInfo.get(0).getCategoryId())).collect(Collectors.toList());
                        if (category.size() > 0) {
                            category.get(0).getParentCategoryDTOList().forEach(cate -> {
                                if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_ONE)) {
                                    dto.setPriCategoryCode(cate.getCategoryCode().toString());
                                    dto.setPriCategoryName(cate.getCategoryName());
                                } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_TWO)) {
                                    dto.setSecCategoryCode(cate.getCategoryCode().toString());
                                    dto.setSecCategoryName(cate.getCategoryName());
                                } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_THREE)) {
                                    dto.setTerCategoryCode(cate.getCategoryCode().toString());
                                    dto.setTerCategoryName(cate.getCategoryName());
                                }
                            });
                        }
                        List<SkuUnitExtDTO> units = skuUnitList.stream().filter(ter -> ter.getSkuCode().equals(skuInfo.get(0).getSkuCode())).collect(Collectors.toList());
                        if (units.size() > 0) {
                            dto.setUnitCode(units.get(0).getUnitCode());
                            dto.setUnitName(units.get(0).getUnitName());
                        }
                        dto.setSkuCode(skuInfo.get(0).getSkuCode());
                        dto.setSkuName(skuInfo.get(0).getSkuName());
                    }
                    dto.setType(type);
                    dto.setChannelCode(readDto.getChannelCode());
                    dto.setChannelName(channelName);
                    dtoList.add(dto);
                } else {
                    if (readDto.getChannelCode().contains(ChannelTypeEnum.CLOUD_BUSINESS.getCode())) {
                        //云商
                        dto.setType(SalesOtherTypeEnum.PLAN_EIGHT.getType());
                        dto.setChannelCode(ChannelTypeEnum.CLOUD_BUSINESS.getCode());
                        dto.setChannelName(ChannelTypeEnum.CLOUD_BUSINESS.getDesc());
                    } else if (readDto.getChannelCode().contains(ChannelTypeEnum.APP.getCode())) {
                        //APP
                        dto.setType(SalesOtherTypeEnum.PLAN_NINE.getType());
                        dto.setChannelCode(ChannelTypeEnum.APP.getCode());
                        dto.setChannelName(ChannelTypeEnum.APP.getDesc());
                    } else if (readDto.getChannelCode().contains(ChannelTypeEnum.DEALER.getCode())) {
                        //经销中心
                        dto.setType(SalesOtherTypeEnum.PLAN_TEN.getType());
                        dto.setChannelCode(ChannelTypeEnum.DEALER.getCode());
                        dto.setChannelName(ChannelTypeEnum.DEALER.getDesc());
                    } else {
                        throw new RomeException(ResponseMsg.FAIL_2015.getCode(), ResponseMsg.FAIL_2015.getMsg());
                    }
                    //如果填了城市
                    List<AreaDTO> city = cityNameList.stream().filter(pro -> ObjectUtil.isNotNull(readDto.getCityName()) && pro.getName().contains(readDto.getCityName())).collect(Collectors.toList());
                    if (city.size() > 0) {
                        if (provinceNameListByCity.size() > 0) {
                            List<AreaDTO> province = provinceNameListByCity.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                            if (province.size() > 0) {
                                dto.setProvinceCode(province.get(0).getCode());
                                dto.setProvinceName(province.get(0).getName());
                            }
                        }
                        dto.setCityCode(city.get(0).getCode());
                        dto.setCityName(city.get(0).getName());
                    } else {
                        //省份必填(填了城市取城市)
                        List<AreaDTO> province = provinceList.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                        if (province.size() > 0) {
                            dto.setProvinceCode(province.get(0).getCode());
                            dto.setProvinceName(province.get(0).getName());
                        }
                    }
                    List<SkuInfoDTO> skuInfo = skus.stream().filter(sku -> sku.getSkuCode().equals(readDto.getSkuCode())).collect(Collectors.toList());
                    if (skuInfo.size() > 0) {
                        List<CategorySimpleDTO> category = categorys.stream().filter(ter -> ter.getId().equals(skuInfo.get(0).getCategoryId())).collect(Collectors.toList());
                        if (category.size() > 0) {
                            category.get(0).getParentCategoryDTOList().forEach(cate -> {
                                if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_ONE)) {
                                    dto.setPriCategoryCode(cate.getCategoryCode().toString());
                                    dto.setPriCategoryName(cate.getCategoryName());
                                } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_TWO)) {
                                    dto.setSecCategoryCode(cate.getCategoryCode().toString());
                                    dto.setSecCategoryName(cate.getCategoryName());
                                } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_THREE)) {
                                    dto.setTerCategoryCode(cate.getCategoryCode().toString());
                                    dto.setTerCategoryName(cate.getCategoryName());
                                }
                            });
                        }
                        List<SkuUnitExtDTO> units = skuUnitList.stream().filter(ter -> ter.getSkuCode().equals(skuInfo.get(0).getSkuCode())).collect(Collectors.toList());
                        if (units.size() > 0) {
                            dto.setUnitCode(units.get(0).getUnitCode());
                            dto.setUnitName(units.get(0).getUnitName());
                        }
                        dto.setSkuCode(skuInfo.get(0).getSkuCode());
                        dto.setSkuName(skuInfo.get(0).getSkuName());
                    }
                    dtoList.add(dto);
                }
            }
        }
        return dtoList;
    }

    /**
     * 表格数据转换为实体类集合(新开店计划)
     *
     * @param readNewStoreList
     * @param skus
     * @param categorys
     * @param provinceList
     * @param cityNameList
     * @param provinceNameListByCity
     * @param skuUnitList
     * @return
     */
    public List<SalesPlanOtherDTO> getNewStoreList
    (List<SalesReadOtherDTO> readNewStoreList, List<SkuInfoDTO> skus, List<CategorySimpleDTO> categorys, List<AreaDTO> provinceList, List<AreaDTO> cityNameList, List<AreaDTO> provinceNameListByCity, List<SkuUnitExtDTO> skuUnitList) {
        List<SalesPlanOtherDTO> dtoList = new ArrayList<>();
        //获取当前时间开始往后5周日期
        //List<Map<String, Date>> dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
        //测试设置获取导入周的时间
        List<String> time = readNewStoreList.stream().filter(item -> ObjectUtil.isNotNull(item.getTime())).map(SalesReadOtherDTO::getTime).collect(Collectors.toList());
        List<Map<String, Date>> dateMap;
        Date importDate;
        if (CollectionUtil.isEmpty(time)) {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(new Date(), CommonConstants.SIX);
            importDate = new Date();
        } else {
            //获取当前时间开始往后5周日期
            dateMap = MyDateUtil.getWeekDates(DateUtil.parseDate(time.get(0)), CommonConstants.SIX);
            importDate = DateUtil.parseDate(time.get(0));
        }
        for (SalesReadOtherDTO readDto : readNewStoreList) {
            int i = 0;
            for (Map<String, Date> week : dateMap) {
                i++;
                if (i == 1) {
                    continue;
                }
                SalesPlanOtherDTO dto = new SalesPlanOtherDTO();
                dto.setPlanImportDate(importDate);
                //当前周不用处理，直接处理当前周往后周的数据
                if (i == 2) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekTwoNum()));
                } else if (i == 3) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekThreeNum()));
                } else if (i == 4) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekFourNum()));
                } else if (i == 5) {
                    dto.setChannelConfirmedQty(new BigDecimal(readDto.getWeekFiveNum()));
                } else if (i == 6) {
                    dto.setChannelConfirmedQty(ObjectUtil.isNotNull(readDto.getWeekSixNum()) ? new BigDecimal(readDto.getWeekSixNum()) : BigDecimal.ZERO);
                } else {
                    dto.setChannelConfirmedQty(ObjectUtil.isNotNull(readDto.getWeekSevenNum()) ? new BigDecimal(readDto.getWeekSevenNum()) : BigDecimal.ZERO);
                }
                //直营
                if (readDto.getChannelCode().equals(ChannelTypeEnum.DIRECTLY_OPERATE.getCode())) {
                    dto.setChannelCode(ChannelTypeEnum.DIRECTLY_OPERATE.getCode());
                    dto.setChannelName(ChannelTypeEnum.DIRECTLY_OPERATE.getDesc());
                    dto.setType(SalesOtherTypeEnum.PLAN_SIX.getType());
                } else if (readDto.getChannelCode().equals(ChannelTypeEnum.JOIN_IN.getCode())) {
                    dto.setChannelCode(ChannelTypeEnum.JOIN_IN.getCode());
                    dto.setChannelName(ChannelTypeEnum.JOIN_IN.getDesc());
                    dto.setType(SalesOtherTypeEnum.PLAN_FIVE.getType());
                } else {
                    throw new RomeException(ResponseMsg.FAIL_2019.getCode(), ResponseMsg.FAIL_2019.getMsg());
                }
                //如果填了城市
                List<AreaDTO> city = cityNameList.stream().filter(pro -> ObjectUtil.isNotNull(readDto.getCityName()) && pro.getName().contains(readDto.getCityName())).collect(Collectors.toList());
                if (city.size() > 0) {
                    if (provinceNameListByCity.size() > 0) {
                        List<AreaDTO> province = provinceNameListByCity.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                        if (province.size() > 0) {
                            dto.setProvinceCode(province.get(0).getCode());
                            dto.setProvinceName(province.get(0).getName());
                        }
                    }
                    dto.setCityCode(city.get(0).getCode());
                    dto.setCityName(city.get(0).getName());
                } else {
                    //省份必填(填了城市取城市)
                    List<AreaDTO> province = provinceList.stream().filter(pro -> pro.getName().contains(readDto.getProvinceName())).collect(Collectors.toList());
                    if (province.size() > 0) {
                        dto.setProvinceCode(province.get(0).getCode());
                        dto.setProvinceName(province.get(0).getName());
                    }
                }
                List<SkuInfoDTO> skuInfo = skus.stream().filter(sku -> sku.getSkuCode().equals(readDto.getSkuCode())).collect(Collectors.toList());
                if (skuInfo.size() > 0) {
                    List<CategorySimpleDTO> category = categorys.stream().filter(ter -> ter.getId().equals(skuInfo.get(0).getCategoryId())).collect(Collectors.toList());
                    if (category.size() > 0) {
                        category.get(0).getParentCategoryDTOList().forEach(cate -> {
                            if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_ONE)) {
                                dto.setPriCategoryCode(cate.getCategoryCode().toString());
                                dto.setPriCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_TWO)) {
                                dto.setSecCategoryCode(cate.getCategoryCode().toString());
                                dto.setSecCategoryName(cate.getCategoryName());
                            } else if (cate.getCategoryLevel().equals(CommonConstants.CATEGORY_LEVEL_THREE)) {
                                dto.setTerCategoryCode(cate.getCategoryCode().toString());
                                dto.setTerCategoryName(cate.getCategoryName());
                            }
                        });
                    }
                    List<SkuUnitExtDTO> units = skuUnitList.stream().filter(ter -> ter.getSkuCode().equals(skuInfo.get(0).getSkuCode())).collect(Collectors.toList());
                    if (units.size() > 0) {
                        dto.setUnitCode(units.get(0).getUnitCode());
                        dto.setUnitName(units.get(0).getUnitName());
                    }
                    dto.setSkuCode(skuInfo.get(0).getSkuCode());
                    dto.setSkuName(skuInfo.get(0).getSkuName());
                }
                dto.setPlanStartDate(week.get("startTime"));
                dto.setPlanEndDate(week.get("endTime"));
                //同步为已确认
                dto.setStatus(SalesConfirmStatusEnum.CONFIRMED.getType());
                dto.setCreator(UserContext.getUserId());
                dto.setCreatorName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dto.setModifier(UserContext.getUserId());
                dto.setModifierName(UserContext.getUserId() == 0 ? "system" : UserContext.getApplicationUser().getUsername());
                dtoList.add(dto);
            }
        }
        return dtoList;
    }


    /**
     * @param excelExportDTO
     * @param type
     * @return
     */
    public ExcelExportDataDTO export(ExcelExportDTO excelExportDTO, Integer type, List<String> channelCodes, Integer level, Long userId) {
        if (ObjectUtil.isNull(type)) {
            throw new RomeException(ResponseMsg.FAIL_2005.getCode(), ResponseMsg.FAIL_2005.getMsg());
        }
        SalesPlanOtherDTO salesPlanOtherDTO = new SalesPlanOtherDTO();
        salesPlanOtherDTO.setLayeredCodeList(excelExportDTO.getLayeredCodeList());
        salesPlanOtherDTO.setChannelCodeList(excelExportDTO.getChannelCodeList());
        salesPlanOtherDTO.setAreaCodeList(excelExportDTO.getAreaCodeList());
        salesPlanOtherDTO.setCategoryCodeList(excelExportDTO.getCategoryCodeList());
        salesPlanOtherDTO.setTypeList(excelExportDTO.getTypeList());
        salesPlanOtherDTO.setPageNum(excelExportDTO.getPageNum());
        salesPlanOtherDTO.setPageSize(excelExportDTO.getPageSize());
        //处理开始时间
        salesPlanOtherDTO.setStartTime(excelExportDTO.getStartTime());
        salesPlanOtherDTO.setUnitType(excelExportDTO.getUnitType());
        List<Map<String, Date>> weekDate = null;
        //选择时间范围导出
        if (ObjectUtil.isNotNull(excelExportDTO.getEndTime())) {
            weekDate = MyDateUtil.getWeekDates(salesPlanOtherDTO.getStartTime(), excelExportDTO.getEndTime());
        } else {
            //根据日期获取间隔日期集合,没有结束时间，默认14周
            weekDate = MyDateUtil.getWeekDates(salesPlanOtherDTO.getStartTime(), CommonConstants.WEEK_SIZE);
        }
        salesPlanOtherDTO.setWeekDateList(weekDate);
        //计算出默认的结束时间
        salesPlanOtherDTO.setEndTime(MyDateUtil.getLastDate(null, weekDate));
        return exportData(salesPlanOtherDTO, type, level, channelCodes, excelExportDTO.getRowIndex(), userId);
    }

    @Override
    public Response downLoadTemplate(String type, String date) {
        if (ObjectUtil.isNull(type)) {
            throw new RomeException(ResponseMsg.FAIL_2005.getCode(), ResponseMsg.FAIL_2005.getMsg());
        }
        return salesPlanOtherFacade.downLoadTemplate(type, date);
    }

    /**
     * 判断是否为整数
     *
     * @param str 传入的字符串
     * @return 是整数返回true, 否则返回false
     */
    private boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public void checkData(SalesReadDTO item, Integer type) {
        //渠道code必填
        if (ObjectUtil.isNull(item.getChannelCode())) {
            throw new RomeException(ResponseMsg.PARAM_ERROR_2014.getCode(), ResponseMsg.PARAM_ERROR_2014.getMsg());
        }
        //省份必填
        if (ObjectUtil.isNull(item.getProvinceName())) {
            throw new RomeException(ResponseMsg.FAIL_2036.getCode(), ResponseMsg.FAIL_2036.getMsg());
        }
        //商品编码必填
        if (ObjectUtil.isNull(item.getSkuCode())) {
            throw new RomeException(ResponseMsg.PARAM_ERROR_2012.getCode(), ResponseMsg.PARAM_ERROR_2012.getMsg());
        }
        if (CommonConstants.ONE.equals(type)) {
            checkIsInteger(null, item, CommonConstants.ONE);
        } else {
            checkIsInteger(null, item, CommonConstants.TWO);
        }
    }

    public void checkOtherData(SalesReadOtherDTO item, Integer type) {
        //渠道code必填
        if (ObjectUtil.isNull(item.getChannelCode())) {
            throw new RomeException(ResponseMsg.PARAM_ERROR_2014.getCode(), ResponseMsg.PARAM_ERROR_2014.getMsg());
        }
        //省份必填
        if (ObjectUtil.isNull(item.getProvinceName())) {
            throw new RomeException(ResponseMsg.FAIL_2036.getCode(), ResponseMsg.FAIL_2036.getMsg());
        }
        //商品编码必填
        if (ObjectUtil.isNull(item.getSkuCode())) {
            throw new RomeException(ResponseMsg.PARAM_ERROR_2012.getCode(), ResponseMsg.PARAM_ERROR_2012.getMsg());
        }
        if (CommonConstants.ONE.equals(type)) {
            checkIsInteger(item, null, CommonConstants.ONE);
        } else {
            checkIsInteger(item, null, CommonConstants.TWO);
        }
    }

    public void checkIsInteger(SalesReadOtherDTO item, SalesReadDTO items, Integer type) {
        if (items == null) {
            if (CommonConstants.ONE.equals(type)) {
                //销售计划当前周前两周必填
                if (ObjectUtil.isNull(item.getWeekTwoNum()) || ObjectUtil.isNull(item.getWeekThreeNum())) {
                    throw new RomeException(ResponseMsg.FAIL_2038.getCode(), ResponseMsg.FAIL_2038.getMsg());
                } else {
                    //是否为整数
                    if (!isInteger(item.getWeekTwoNum()) || !isInteger(item.getWeekThreeNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekFourNum())) {
                    if (!isInteger(item.getWeekFourNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekFiveNum())) {
                    if (!isInteger(item.getWeekFiveNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekSixNum())) {
                    if (!isInteger(item.getWeekSixNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekSevenNum())) {
                    if (!isInteger(item.getWeekSevenNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
            } else {
                //新品铺货计划当前周前四周必填
                if (ObjectUtil.isNull(item.getWeekTwoNum()) || ObjectUtil.isNull(item.getWeekThreeNum()) || ObjectUtil.isNull(item.getWeekFourNum()) || ObjectUtil.isNull(item.getWeekFiveNum())) {
                    throw new RomeException(ResponseMsg.FAIL_2040.getCode(), ResponseMsg.FAIL_2040.getMsg());
                } else {
                    //是否为整数
                    if (!isInteger(item.getWeekTwoNum()) || !isInteger(item.getWeekThreeNum()) || !isInteger(item.getWeekFourNum()) || !isInteger(item.getWeekFiveNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekSixNum())) {
                    if (!isInteger(item.getWeekSixNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(item.getWeekSevenNum())) {
                    if (!isInteger(item.getWeekSevenNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
            }
        } else {
            if (CommonConstants.ONE.equals(type)) {
                //销售计划当前周前两周必填
                if (ObjectUtil.isNull(items.getWeekTwoNum()) || ObjectUtil.isNull(items.getWeekThreeNum())) {
                    throw new RomeException(ResponseMsg.FAIL_2038.getCode(), ResponseMsg.FAIL_2038.getMsg());
                } else {
                    //是否为整数
                    if (!isInteger(items.getWeekTwoNum()) || !isInteger(items.getWeekThreeNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekFourNum())) {
                    if (!isInteger(items.getWeekFourNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekFiveNum())) {
                    if (!isInteger(items.getWeekFiveNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekSixNum())) {
                    if (!isInteger(items.getWeekSixNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekSevenNum())) {
                    if (!isInteger(items.getWeekSevenNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
            } else {
                //新品铺货计划当前周前四周必填
                if (ObjectUtil.isNull(items.getWeekTwoNum()) || ObjectUtil.isNull(items.getWeekThreeNum()) || ObjectUtil.isNull(items.getWeekFourNum()) || ObjectUtil.isNull(items.getWeekFiveNum())) {
                    throw new RomeException(ResponseMsg.FAIL_2040.getCode(), ResponseMsg.FAIL_2040.getMsg());
                } else {
                    //是否为整数
                    if (!isInteger(items.getWeekTwoNum()) || !isInteger(items.getWeekThreeNum()) || !isInteger(items.getWeekFourNum()) || !isInteger(items.getWeekFiveNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekSixNum())) {
                    if (!isInteger(items.getWeekSixNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
                //填的必须为整数
                if (ObjectUtil.isNotNull(items.getWeekSevenNum())) {
                    if (!isInteger(items.getWeekSevenNum())) {
                        throw new RomeException(ResponseMsg.FAIL_2041.getCode(), ResponseMsg.FAIL_2041.getMsg());
                    }
                }
            }
        }
    }

    private void checkChannelSkuPermit(List<SalesReadDTO> salesReadList, List<SalesReadOtherDTO> salesOtherReadList, Integer type) {
        //到门店
        if (salesOtherReadList == null) {
            if (CommonConstants.ONE.equals(type)) {
                //根据渠道分组
                Map<String, List<SalesReadDTO>> dtoMap = salesReadList.stream().filter(item -> !ChannelTypeEnum.DIRECTLY_OPERATE.getCode().equals(item.getChannelCode()) && !ChannelTypeEnum.JOIN_IN.getCode().equals(item.getChannelCode())).collect(Collectors.groupingBy(group -> group.getChannelCode()));
                dtoMap.forEach((k, v) -> {
                    //获取所有不重复的商品编码
                    List<String> skusList = v.stream().map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                    categoryFacade.queryWidthSku(k, null, null, null, skusList);
                });
            } else {
                //获取只有省的数据（校验商品是否可以叫货）
                List<SalesReadDTO> proList = salesReadList.stream().filter(item -> ObjectUtil.isNull(item.getCityName()) && ObjectUtil.isNull(item.getStoreCode())).collect(Collectors.toList());
                if (proList.size() > 0) {
                    //根据渠道、省份名称分组（一次导入有多个渠道）
                    Map<String, List<SalesReadDTO>> proMap = proList.stream().collect(Collectors.groupingBy(group -> group.getChannelCode() + "--" + group.getProvinceName()));
                    proMap.forEach((k, v) -> {
                        //获取所有不重复的商品编码
                        List<String> skusList = v.stream().map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                        String provinceCode = "";
                        try {
                            List<String> pros = new ArrayList<>();
                            pros.add(k.split("--")[1]);
                            provinceCode = baseDataFacade.listProvinceByList(pros).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + k.split("--")[1]);
                        }
                        categoryFacade.queryWidthSku(k.split("--")[0], provinceCode, null, null, skusList);

                    });
                }
                //获取到市的数据（校验商品是否可以叫货）
                List<SalesReadDTO> cityList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName()) && ObjectUtil.isNull(item.getStoreCode())).collect(Collectors.toList());
                if (cityList.size() > 0) {
                    //根据渠道、省份、市名称分组（一次导入有多个渠道）
                    Map<String, List<SalesReadDTO>> proMap = cityList.stream().collect(Collectors.groupingBy(group -> group.getChannelCode() + "--" + group.getProvinceName() + "--" + group.getCityName()));
                    proMap.forEach((k, v) -> {
                        //获取所有不重复的商品编码
                        List<String> skuss = v.stream().map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                        String proCode = "";
                        String cityCode = "";
                        try {
                            List<String> pros = new ArrayList<>();
                            pros.add(k.split("--")[1]);
                            proCode = baseDataFacade.listProvinceByList(pros).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + k.split("--")[1]);
                        }
                        try {
                            List<String> citys = new ArrayList<>();
                            citys.add(k.split("--")[2]);
                            cityCode = baseDataFacade.listProvinceByList(citys).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + k.split("--")[2]);
                        }
                        categoryFacade.queryWidthSku(k.split("--")[0], proCode, cityCode, null, skuss);
                    });
                }
                //获取到门店的数据（校验商品是否可以叫货）
                List<SalesReadDTO> storesList = salesReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getStoreCode())).collect(Collectors.toList());
                if (storesList.size() > 0) {
                    //根据门店编码分组（一次导入只有一个渠道）
                    Map<String, List<SalesReadDTO>> proMap = storesList.stream().collect(Collectors.groupingBy(group -> group.getChannelCode() + "--" + group.getStoreCode()));
                    proMap.forEach((k, v) -> {
                        StoreDTO storeDto = new StoreDTO();
                        storeDto.setCode(k.split("--")[1]);
                        List<StoreDTO> storeList = baseDataFacade.listStore(storeDto).getList();
                        //获取所有不重复的商品编码
                        List<String> skus = v.stream().map(SalesReadDTO::getSkuCode).distinct().collect(Collectors.toList());
                        categoryFacade.queryWidthSku(k.split("--")[0], storeList.get(0).getProvinceCode(), storeList.get(0).getCityCode(), k.split("--")[1], skus);
                    });
                }
            }
        } else {
            //没有门店字段
            if (CommonConstants.ONE.equals(type)) {
                //根据渠道分组
                Map<String, List<SalesReadOtherDTO>> dtoMap = salesOtherReadList.stream().filter(item -> !ChannelTypeEnum.DIRECTLY_OPERATE.getCode().equals(item.getChannelCode()) && !ChannelTypeEnum.JOIN_IN.getCode().equals(item.getChannelCode())).collect(Collectors.groupingBy(group -> group.getChannelCode()));
                dtoMap.forEach((k, v) -> {
                    //获取所有不重复的商品编码
                    List<String> skusList = v.stream().map(SalesReadOtherDTO::getSkuCode).distinct().collect(Collectors.toList());
                    categoryFacade.queryWidthSku(k, null, null, null, skusList);
                });
            } else {
                //获取只有省的数据（校验商品是否可以叫货）
                List<SalesReadOtherDTO> proList = salesOtherReadList.stream().filter(item -> ObjectUtil.isNull(item.getCityName())).collect(Collectors.toList());
                if (proList.size() > 0) {
                    //根据渠道、省份名称分组（一次导入有多个渠道）
                    Map<String, List<SalesReadOtherDTO>> proMap = proList.stream().collect(Collectors.groupingBy(group -> group.getChannelCode() + "--" + group.getProvinceName()));
                    proMap.forEach((k, v) -> {
                        //获取所有不重复的商品编码
                        List<String> skusList = v.stream().map(SalesReadOtherDTO::getSkuCode).distinct().collect(Collectors.toList());
                        String provinceCode = "";
                        try {
                            List<String> pros = new ArrayList<>();
                            pros.add(k.split("--")[1]);
                            provinceCode = baseDataFacade.listProvinceByList(pros).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + k.split("--")[1]);
                        }
                        categoryFacade.queryWidthSku(k.split("--")[0], provinceCode, null, null, skusList);
                    });
                }
                //获取到市的数据（校验商品是否可以叫货）
                List<SalesReadOtherDTO> cityList = salesOtherReadList.stream().filter(item -> ObjectUtil.isNotNull(item.getCityName())).collect(Collectors.toList());
                if (cityList.size() > 0) {
                    //根据渠道、省份、市名称分组（一次导入有多个渠道）
                    Map<String, List<SalesReadOtherDTO>> proMap = cityList.stream().collect(Collectors.groupingBy(group -> group.getChannelCode() + "--" + group.getProvinceName() + "--" + group.getCityName()));
                    proMap.forEach((k, v) -> {
                        //获取所有不重复的商品编码
                        List<String> skuss = v.stream().map(SalesReadOtherDTO::getSkuCode).distinct().collect(Collectors.toList());
                        String proCode = "";
                        String cityCode = "";
                        try {
                            List<String> pros = new ArrayList<>();
                            pros.add(k.split("--")[1]);
                            proCode = baseDataFacade.listProvinceByList(pros).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2043.getCode(), ResponseMsg.FAIL_2043.getMsg() + k.split("--")[1]);
                        }
                        try {
                            List<String> citys = new ArrayList<>();
                            citys.add(k.split("--")[2]);
                            cityCode = baseDataFacade.listProvinceByList(citys).get(0).getCode();
                        } catch (Exception e) {
                            throw new RomeException(ResponseMsg.FAIL_2042.getCode(), ResponseMsg.FAIL_2042.getMsg() + k.split("--")[2]);
                        }
                        categoryFacade.queryWidthSku(k.split("--")[0], proCode, cityCode, null, skuss);
                    });
                }
            }
        }
    }

    @Override
    public List<SalesWriteDTO> getLastWeekByType() {
        return salesPlanOtherFacade.getLastWeekByType();
    }


    /**
     * 汇总分组后的数据
     *
     * @param paramMap       参数映射
     * @param salesPlanOther 其他渠道计划
     * @param level          级别
     * @param type           类型 1：柱状图
     * @return {@link List<SalesPlanOtherInfoDTO>}
     */
    /*private List<SalesPlanOtherInfoDTO> getTargetList(List<Map<String, Object>> paramMap, SalesPlanOtherDTO salesPlanOther, Integer level, Integer type*//*, List<SalesPlanOtherTypeDTO> typeList, List<SalesPlanOtherTypeDTO> typeImpList*//*) {
        if (paramMap.size() == 0) {
            return Collections.emptyList();
        }
        List<SalesPlanOtherInfoDTO> salesPlanOtherInfoList = new ArrayList<>();
        List<Map<String, Date>> weekDateList = salesPlanOther.getWeekDateList();
        //查询唯一一条数据对应的14周时间集合
        Map<String, List<Map<String, Object>>> mapList = paramMap.stream().collect(Collectors.groupingBy
                (item -> (ObjectUtil.isNotNull(item.get("channel")) ? item.get("channel").toString() : "")
                        + (ObjectUtil.isNotNull(item.get("plan_type")) ? item.get("plan_type").toString() : "") + (ObjectUtil.isNotNull(item.get("province")) ? item.get("province").toString() : "")
                        + (ObjectUtil.isNotNull(item.get("city")) ? item.get("city").toString() : "")
                        + (ObjectUtil.isNotNull(item.get("node_id")) ? item.get("node_id").toString() : "") + (ObjectUtil.isNotNull(item.get("sku_key")) ? item.get("sku_key").toString() : "")
                ));
        Map<String, ChannelDTO> channelMap = new HashMap<>();
        Map<String, BaseSkuInfoDTO> skuInfoMap = new HashMap<>();
        Map<String, StoreDTO> storeMap = new HashMap<>();
        *//*if (!CommonConstants.ONE.equals(type)) {
            //获取所有渠道
            channelMap = redisCacheFacade.getAllChannelInfo();
            List<String> skuList = paramMap.stream().map(e -> e.get("sku_key").toString()).distinct().collect(Collectors.toList());
            //根据sku集合获取所有品类信息
            skuInfoMap = redisCacheFacade.getCategoryInfoBySkuCodes(skuList);
            List<String> storeList = paramMap.stream().map(e -> e.get("node_id").toString()).distinct().collect(Collectors.toList());
            //根据门店获取区域信息
            storeMap = redisCacheFacade.getStoreInfoByCodes(storeList);
        }*//*
        //将分组后的数据转换为页面展示的DTO
        mapList.forEach((k, v) -> {
            //上次计划量
            List<BigDecimal> lastPlanQtys = new ArrayList<>();
            //上次确认量
            List<BigDecimal> lastConfirmedQtys = new ArrayList<>();
            //计划量
            List<BigDecimal> planQtys = new ArrayList<>();
            //确认量
            List<BigDecimal> confirmedQtys = new ArrayList<>();
            //下级确认量
            List<BigDecimal> subordinateConfirms = new ArrayList<>();
            //计划差异
            List<BigDecimal> planDifferences = new ArrayList<>();
            //计划比例
            List<BigDecimal> planProportions = new ArrayList<>();
            //渠道确认量
            List<BigDecimal> channelConfirmedQtys = new ArrayList<>();
            //全渠道确认量
            List<BigDecimal> allchannelConfirmedQtys = new ArrayList<>();
            //渠道上次确认量
            List<BigDecimal> channelLastConfirmedQtys = new ArrayList<>();
            //全渠道上次确认量
            List<BigDecimal> allchannelLastConfirmedQtys = new ArrayList<>();
            SalesPlanOtherInfoDTO salesPlanOtherInfo = new SalesPlanOtherInfoDTO();
            //上次计划量
            weekDateList.forEach(date -> lastPlanQtys.add(v.stream().filter(item ->
                    DateUtil.parseDate(item.get("start_date").toString()).
                            compareTo(date.get("startTime")) == 0)
                    .map(e -> new BigDecimal(e.get("last_predict_sales").toString()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add)));
            salesPlanOtherInfo.setLastPlanQtyLabel(SalesPlanOtherEnum.LAST_PLAN_QTY.getDesc());
            salesPlanOtherInfo.setLastPlanQtys(lastPlanQtys);
            //计划量
            weekDateList.forEach(date -> planQtys.add(v.stream().filter(item ->
                    DateUtil.parseDate(item.get("start_date").toString()).
                            compareTo(date.get("startTime")) == 0)
                    .map(e -> new BigDecimal(e.get("predict_sales").toString()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add)));

            salesPlanOtherInfo.setPlanQtyLabel(SalesPlanOtherEnum.PLAN_QTY.getDesc());
            salesPlanOtherInfo.setPlanQtys(planQtys);
            //2级全渠道用户
            if (level.equals(CommonConstants.OTHER_PLAN_LEVEL_TWO)) {
                //上次确认量
                weekDateList.forEach(date -> lastConfirmedQtys.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("last_confirm_l4").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //确认量
                weekDateList.forEach(date -> confirmedQtys.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("confirm_l4").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //计划差异
                weekDateList.forEach(date -> planDifferences.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("predict_confirm_l4_difference").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //计划比例
                weekDateList.forEach(date -> planProportions.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("predict_confirm_l4_scale").toString().substring(0, 4)))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //下级确认量
                weekDateList.forEach(date -> subordinateConfirms.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("confirm_l3").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                salesPlanOtherInfo.setSubordinateConfirmedQtyLabel(SalesPlanOtherEnum.SUBORDINATE_CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setSubordinateConfirmedQtys(subordinateConfirms);
            } else {
                //上次确认量
                weekDateList.forEach(date -> lastConfirmedQtys.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("last_confirm_l3").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //确认量
                weekDateList.forEach(date -> confirmedQtys.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("confirm_l3").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //计划差异
                weekDateList.forEach(date -> planDifferences.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("predict_confirm_l3_difference").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
                //计划比例
                weekDateList.forEach(date -> planProportions.add(v.stream().filter(item ->
                        DateUtil.parseDate(item.get("start_date").toString()).
                                compareTo(date.get("startTime")) == 0)
                        .map(e -> new BigDecimal(e.get("predict_confirm_l3_scale").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)));
            }
            salesPlanOtherInfo.setLastConfirmedQtyLabel(SalesPlanOtherEnum.LAST_CONFIRMED_QTY.getDesc());
            salesPlanOtherInfo.setLastConfirmedQtys(lastConfirmedQtys);
            salesPlanOtherInfo.setConfirmedQtyLabel(SalesPlanOtherEnum.CONFIRMED_QTY.getDesc());
            salesPlanOtherInfo.setConfirmedQtys(confirmedQtys);
            salesPlanOtherInfo.setPlanDifferenceLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_DIFFERIN.getDesc());
            salesPlanOtherInfo.setPlanProportionLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_PROPORTION.getDesc());
            salesPlanOtherInfo.setPlanDifferences(planDifferences);
            salesPlanOtherInfo.setPlanProportions(planProportions);
            if (!CommonConstants.ONE.equals(type)) {
                salesPlanOtherInfo.setChannel(v.get(0).get("channel").toString());
                List<Integer> statusList = new ArrayList<>();
                List<String> typeList = new ArrayList<>();
                List<String> businessNoList = new ArrayList<>();
                //14周的确认状态
                weekDateList.forEach(date -> {
                    List<Integer> stas = v.stream().
                            filter(item ->
                                    DateUtil.parseDate(item.get("start_date").toString()).
                                            compareTo(date.get("startTime")) == 0)
                            .map(e -> Integer.valueOf(e.get("confirm_status_l4").toString()))
                            .collect(Collectors.toList());
                    if (stas.size() == 0) {
                        //1表示不能修改，0可以修改
                        Integer st = 1;
                        stas = new ArrayList<>();
                        stas.add(st);
                    }
                    statusList.addAll(stas);
                });

                //14周的计划类型
                weekDateList.forEach(date -> {
                    List<String> types = v.stream().
                            filter(item ->
                                    DateUtil.parseDate(item.get("start_date").toString()).
                                            compareTo(date.get("startTime")) == 0)
                            .map(e -> e.get("plan_type").toString())
                            .collect(Collectors.toList());
                    if (types.size() == 0) {
                        //18表示不能修改
                        String typ = "18";
                        types = new ArrayList<>();
                        types.add(typ);
                    }
                    typeList.addAll(types);
                });
                //no(唯一)修改确认量用
                weekDateList.forEach(date -> {
                    List<String> nos = v.stream().
                            filter(item ->
                                    DateUtil.parseDate(item.get("start_date").toString()).
                                            compareTo(date.get("startTime")) == 0)
                            .map(e -> e.get("business_no").toString())
                            .collect(Collectors.toList());
                    if (nos.size() == 0) {
                        //没有数据NO用-1表示
                        String no = "-1";
                        nos = new ArrayList<>();
                        nos.add(no);
                    }
                    businessNoList.addAll(nos);
                });
                salesPlanOtherInfo.setBusinessNo(businessNoList);
                salesPlanOtherInfo.setStatusList(statusList);
                salesPlanOtherInfo.setTypeList(typeList);
                salesPlanOtherInfo.setType(SalesOtherTypeEnum.getNameByType(v.get(0).get("plan_type").toString()));
                salesPlanOtherInfo.setSkuName(v.get(0).get("sku_key").toString());
                //获取品类
                salesPlanOtherInfo.setCategory((!ObjectUtils.isEmpty(v.get(0).get("cate_l4").toString()) ? v.get(0).get("cate_l4").toString() : "") +
                        (!ObjectUtils.isEmpty(v.get(0).get("cate_l3").toString()) ? "/" + v.get(0).get("cate_l3").toString() : "") + (!ObjectUtils.isEmpty(v.get(0).get("cate_l2").toString()) ? "/" + v.get(0).get("cate_l2").toString() : ""));
                salesPlanOtherInfo.setArea((!ObjectUtils.isEmpty(v.get(0).get("province").toString()) ? v.get(0).get("province").toString() : "")
                        + (!ObjectUtils.isEmpty(v.get(0).get("city").toString()) ? "/" + v.get(0).get("city").toString() : "") + (!ObjectUtils.isEmpty(v.get(0).get("district").toString()) ? "/" + v.get(0).get("district").toString() : "") + (!ObjectUtils.isEmpty(v.get(0).get("node_id").toString()) ? "/" + v.get(0).get("node_id").toString() : "")
                );
            }
            salesPlanOtherInfoList.add(salesPlanOtherInfo);
        });
        return salesPlanOtherInfoList;
    }*/

    /**
     * @param list
     * @param level
     * @param type
     * @return
     */
    public List<SalesPlanOtherInfoDTO> getNewTargetList(List<EsReturnDTO> list, Integer level, Integer type) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<SalesPlanOtherInfoDTO> infoList = new ArrayList<>();
        list.forEach(item -> {
            SalesPlanOtherInfoDTO salesPlanOtherInfo = new SalesPlanOtherInfoDTO();
            //柱状图只查询指标数量
            if (type == null) {
                salesPlanOtherInfo.setChannel(item.getChannelName());
                salesPlanOtherInfo.setChannelCode(item.getChannel());
                salesPlanOtherInfo.setType(SalesOtherTypeEnum.getNameByType(item.getPlanType().toString()));
                List<String> typeList = new ArrayList<>();
                //方便前台查询是否可以确认
                for (int i = 0; i < 14; i++) {
                    typeList.add(item.getPlanType().toString());
                }
                salesPlanOtherInfo.setTypeList(typeList);
                salesPlanOtherInfo.setArea(item.getArea());
                salesPlanOtherInfo.setAreaCode(item.getAreaCode());
                salesPlanOtherInfo.setSkuCode(item.getSkuCode());
                salesPlanOtherInfo.setSkuName(item.getSkuCode() + "/" + item.getSkuName());
                salesPlanOtherInfo.setCategory(item.getCategory());
                item.getTargetMap().forEach((k, v) -> {
                    //确认状态
                    if (EsSumColumnEnum.CONFIRM_STATUS_L4.getColumn().equals(k)) {
                        List<Integer> integerList = new ArrayList<>();
                        v.forEach(in -> {
                            integerList.add(in.intValue());
                        });
                        salesPlanOtherInfo.setStatusList(integerList);
                    }
                });
            }
            //实际销量
            salesPlanOtherInfo.setActualSalesQtyLabel(OtherTargetsEnum.ACTUAL_SALES.getDesc());
            salesPlanOtherInfo.setActualSalesQty(item.getTargetMap().get(OtherTargetsEnum.ACTUAL_SALES.getName()));
            //计划量
            salesPlanOtherInfo.setPlanQtyLabel(SalesPlanOtherEnum.PLAN_QTY.getDesc());
            salesPlanOtherInfo.setPlanQtys(item.getTargetMap().get(EsSumColumnEnum.PREDICT_SALES.getColumn()));
            //上次计划量
            salesPlanOtherInfo.setLastPlanQtyLabel(SalesPlanOtherEnum.LAST_PLAN_QTY.getDesc());
            salesPlanOtherInfo.setLastPlanQtys(item.getTargetMap().get(EsSumColumnEnum.LAST_PREDICT_SALES.getColumn()));
            //2级全渠道用户
            if (level.equals(CommonConstants.OTHER_PLAN_LEVEL_TWO)) {
                salesPlanOtherInfo.setConfirmedQtyLabel(SalesPlanOtherEnum.CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setConfirmedQtys(item.getTargetMap().get(EsSumColumnEnum.CONFIRM_L4.getColumn()));
                salesPlanOtherInfo.setLastConfirmedQtyLabel(SalesPlanOtherEnum.LAST_CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setLastConfirmedQtys(item.getTargetMap().get(EsSumColumnEnum.LAST_CONFIRM_L4.getColumn()));
                salesPlanOtherInfo.setSubordinateConfirmedQtyLabel(SalesPlanOtherEnum.SUBORDINATE_CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setSubordinateConfirmedQtys(item.getTargetMap().get(EsSumColumnEnum.CONFIRM_L3.getColumn()));
                salesPlanOtherInfo.setPlanDifferenceLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_DIFFERIN.getDesc());
                salesPlanOtherInfo.setPlanDifferences(item.getTargetMap().get(EsSumColumnEnum.PREDICT_CONFIRM_L4_DIFFERENCE.getColumn()));
                salesPlanOtherInfo.setPlanProportionLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_PROPORTION.getDesc());
                salesPlanOtherInfo.setPlanProportions(item.getTargetMap().get(EsSumColumnEnum.PREDICT_CONFIRM_L4_SCALE.getColumn()));
            } else {
                salesPlanOtherInfo.setConfirmedQtyLabel(SalesPlanOtherEnum.CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setConfirmedQtys(item.getTargetMap().get(EsSumColumnEnum.CONFIRM_L3.getColumn()));
                salesPlanOtherInfo.setLastConfirmedQtyLabel(SalesPlanOtherEnum.LAST_CONFIRMED_QTY.getDesc());
                salesPlanOtherInfo.setLastConfirmedQtys(item.getTargetMap().get(EsSumColumnEnum.LAST_CONFIRM_L3.getColumn()));
                salesPlanOtherInfo.setPlanDifferenceLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_DIFFERIN.getDesc());
                salesPlanOtherInfo.setPlanDifferences(item.getTargetMap().get(EsSumColumnEnum.PREDICT_CONFIRM_L3_DIFFERENCE.getColumn()));
                salesPlanOtherInfo.setPlanProportionLabel(SalesPlanOtherEnum.PLAN_CONFIRMED_PROPORTION.getDesc());
                salesPlanOtherInfo.setPlanProportions(item.getTargetMap().get(EsSumColumnEnum.PREDICT_CONFIRM_L3_SCALE.getColumn()));
            }
            infoList.add(salesPlanOtherInfo);
        });
        return infoList;
    }

    @Override
    public OperationLogRecordDTO saveOperatorLog(ExcelExportDTO excelExportDTO, Integer type) {
        OperationLogRecordDTO operationDto = new OperationLogRecordDTO();
        Long userId = UserContext.getUserId();
        operationDto.setOpContent(OperationSourceEnum.FOUR_PLAN.getDesc() + "-" + type);
        operationDto.setOpType(OperationTypeEnum.EXPORT.getType());
        operationDto.setOpStatus(OperationStatusEnum.PROCESSING.getType());
        operationDto.setOpSource(OperationSourceEnum.FOUR_PLAN.getTableType());
        operationDto.setCreateTime(new Date());
        operationDto.setUpdateTime(new Date());
        operationDto.setCreator(userId);
        operationDto.setCreatorName(userId == 0 ? "system" : UserContext.getApplicationUser().getUsername());
        return operationLogRecordFacade.insertOperationLog(operationDto);
    }

    @Async
    @Override
    public void createExportFile(OperationLogRecordDTO operationDto, ExcelExportDTO excelExportDTO, Integer type, List<String> channelCodes, Integer level, Long userId) {
        Integer opStatus = OperationStatusEnum.SUCCESS.getType();
        String ext = "";
        try {
            ExcelExportDataDTO excelExportDataDTO = this.export(excelExportDTO, type, channelCodes, level, userId);
            // 指定文件夹
            String folderName = OperationSourceEnum.FOUR_PLAN.getTableType().toString();
            //获取文件名
            String fileName = ExcelExportUtil.getFileName(OperationSourceEnum.FOUR_PLAN.getDesc(), userId, type);
            //写文件并返回路径
            ext = ExcelExportUtil.exportExcel(excelExportDataDTO, folderName, filePath, fileName);
        } catch (RomeException e) {
            opStatus = OperationStatusEnum.FAIL.getType();
            operationDto.setFailReason(e.getMessage());
            log.error("其他渠道计划导入失败", e);
        } catch (Exception e) {
            opStatus = OperationStatusEnum.FAIL.getType();
            operationDto.setFailReason("导出失败");
            log.error("其他渠道计划导入失败", e);
        }
        operationDto.setExt(ext);
        operationDto.setOpStatus(opStatus);
        operationDto.setOpEndTime(new Date());
        operationLogRecordFacade.updateOperationLog(operationDto);
    }

    public void startImportPlan(List<SalesPlanOtherDTO> salesOtherList, Integer impType, Long id) {
        //异步新增导入计划数据
        new Thread((() -> {
            try {
                log.info("-------异步新增导入计划数据开始------");
                salesPlanOtherFacade.importPlanType(salesOtherList, impType, id);
            } catch (Exception ex) {
                log.info("异步新增导入计划数据异常，" + ex);
            }
            log.info("-------异步新增导入计划数据结束------");
        })).start();
    }
}
